Search code examples
c#asp.net-mvcasp.net-mvc-4remote-validation

ASP.net MVC 4 Remote Validation does not work


I try to validate a String in a EditorFor.. If the Licence is not in my Database I want to print an Error..

Here is my Model:

    [Display(Name = "Lizenznummer")] 
    [Required]
    [Remote("IsLicenseValid", "HLRController", "Lizenznummer ungültig")]    
    public string HLR_LIZENZ { get; set; }

Here is my Controller (HLRController.cs)

    public ActionResult IsLicenseValid(string HLR_LIZENZ)
    {
        return IsExist(HLR_LIZENZ)
            ? Json(true, JsonRequestBehavior.AllowGet)
            : Json(string.Format("{0} ist nicht gültig.", HLR_LIZENZ),
                    JsonRequestBehavior.AllowGet);
        //: Json(false, JsonRequestBehavior.AllowGet);


    }

    public bool IsExist(string license)
    {
        bool result = false;

        var item = (from c in db.KD select c).ToArray();

        for (int i = 0; i < item.Length; i++)
        {
            if (item[i].KD_LIZENZ == license)
                result = true;

            if (result)
                break;
        }           

        return result;
    }

And there is my View:

    <div class="editor-field">
    @Html.EditorFor(model => model.HLR_LIZENZ)
    @Html.ValidationMessageFor(model => model.HLR_LIZENZ)
    </div>

I dont know where I went wrong.. I saw similar code here, and on other pages in the internet -.-

If I test this code, nothing happens. Ok, nothing is a lie. If I write a licence in my EditFor nothing happens - but the [Required] Vaidation does not work. If the field is empty he writes the ErrorMessage and he frames the field in red. Then I type in something - the red frame disappear but the ErrorMessage stays.

I wanted to debug this and I put a BreakPoint into my "IsLicenseValid" Method - but he dont stop there. So this method is never been used.. (?!)

Has someone an idea? Thanks a lot!


Solution

  • You have to omit controller part in the controller name of your attribute, it is handled by the framework:

    [Remote("IsLicenseValid", "HLR", "Lizenznummer ungültig")]