1

1. Project specification

Mission: Check if user enters unique dictionary name.

Model (all entities in my project are in separate class):

public class Dictionary
{
    [Required]
    [Index("IX_Dictionary_Name_UK", IsUnique = true)]
    [MaxLength(100)]
    [Display(Name="Name")]
    [Remote("DictionaryNameExists", "Administrator", ErrorMessage = "Dictionary name already exists in the database!")]
    public string Name { get; set; }        
}

Controller:

[Authorize(Roles="Administrator")]
public class AdministratorController : BaseController
{

    public AdministratorController(IDictionaryRepository dictionaryRepository)
    {
        this.dictionaryRepository = dictionaryRepository;
        this.dictionaryModel = new DictionaryModel(); 
    }

    [AllowAnonymous]
    public JsonResult DictionaryNameExists(string Name)
    {
        return Json(dictionaryRepository.DictionaryNameExists(Name), JsonRequestBehavior.AllowGet);
    } 

}

View:

@using (Html.BeginForm("AddEditDictionary", "Administrator")){
<div id="dictionaryContainer" class="modal-body">

    <fieldset>
        <div class="editor-label">
            @Html.LabelFor(model => model.Dictionary.Name)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Dictionary.Name)
            @Html.ValidationMessageFor(model => model.Dictionary.Name)
        </div>
    </fieldset>

</div>
<div class="modal-footer">
    <button id="btnSaveChanges" type="submit" name="command" value="Save" class="btn btn-primary">Save dictionary</button>
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>}

Above View is a PartialView which I'm including into bootstrap modal by ajax query as follows:

function MakeGetRequest() {
    var url = "/Administrator/AddDictionary/";

    $.get(url, function (data) {
        $("#containerId").html(data);
        $("#modalId").modal('show');
    });
}

2. Problem

DictionaryNameExists method is not triggering. I have set breakpoint there and it's not 'hitting' it. Secondly, ModelState.IsValid is always true, even when I entered existing name. ModelState.IsValid works properly for MaxLengthAttribute and RequiredAttribute.

3. Whathaveyoutried.com

  • I have enabled settings in web.config (ClientValidationEnabled and UnobtrusiveJavaScriptEnabled)
  • I've added an attribute to my controller as follows:

    [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]

  • I've added HttpGet attribute to method and to RemoteAttribute also.

  • I've included javascript libraries
  • Server properly generated my tags:

... data-val-remote="Dictionary name already exists in the database!" data-val-remote-additionalfields="*.Name" data-val-remote-url="/Administrator/DictionaryNameExists"...

  • As Darin answered I've added his code to my "MakeGetRequestFunction"
  • Finally I've cleared browser (Chrome) cache.
  • My ViewModel is a class which contains my Entity class, so my thought was to Bind my property, but it also didn't worked for me

4. What now?

I can make custom attribute, but I have model in separate library, so I cannot inject there my repository for checking uniqueness. For the same reason I can't use such library as FluentValidation. I belive there is simple reason why my Action is not firing. I'm asking for your help.

Community
  • 1
  • 1
  • You have decorated the Controller with Authorize attribute and DictionaryNameExists is also in this controller so shouldn't this be a problem ? – Mairaj Ahmad Dec 30 '14 at 04:34
  • That was my first thought, so I used [AllowAnonymous] on my method. It didn't help. But thanks for your time. – Karol Miszczyk Dec 30 '14 at 13:34

1 Answers1

0

Because your content are loaded after the validation call. You need to call the validation and parse from after loading the partial view.

$.get(url, function (data) {
    $("#containerId").html(data);
    $("#modalId").modal('show');
    var form = $('form');
    form.removeData('validator');
    form.removeData('unobtrusiveValidation');
    $.validator.unobtrusive.parse(form);
});
Mohsen Esmailpour
  • 11,224
  • 3
  • 45
  • 66
  • Thanks it solved my problem. So here was my mistake. I did remove data from validator, but I did it after $.get(url, function (data){}); not inside this construction. – Karol Miszczyk Dec 30 '14 at 13:37