Search code examples
asp.net-mvcjquery-validateasp.net-mvc-4

MVC AJAX property validation


I have a create user view (action) and apart from the clientside validations of certain field types, date, emailaddress etc i want to check that a couple for example emailaddress and username are unique by calling a couple of Server controlleractions.

I would have thought it preferable to "hook" into the existing MVC validation mechanisms to call these ajax functions. So that all when form validation occurs it calls my ajax validators, and restrospectively reflects this in the modelstate.isvalid, and on any errors are shown in the default html.validation helpers.

I was unsure if this is possible or if i needed to handle my own validation seperately? Currently i have created a couple of jquery functions which call a couple of controller actions and display the validity state of the username and emailaddress in a couple of spans i have added.

What is the best pattern with MVC? I thought about the possible method of wrapping each of the above fields in a seperate @Ajax.BeginForm(


Solution

  • There is built in remote validation in Asp.Net MVC.

    In model:

    public class CreateUserModel 
    {
        [Remote("IsNameAvailable", "Validation")]
        public override string UserName { get; set; }
    }
    

    In controller:

    public class ValidationController : Controller 
    {
        public JsonResult IsNameAvailable(string Username) 
        {
            ... Do some checks
            return Json({some validation message here}, JsonRequestBehavior.AllowGet);
        }
    
    }