Friday, April 19, 2013

How to add ajax validation on field in ASP.NET MVC 3?
By Remote Attribute. This way is MS designed for you.

//In Model
        [Remote("CheckExistedEmail", "ControllerName")]
        [Required]
        [DataType(DataType.EmailAddress)]
        [Display(Name = "Email address")]
        [RegularExpression(@"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$",ErrorMessage="Invalid email address")]
        public string Email { get; set; }

//In Action 
        public JsonResult CheckExistedEmail(string Email)
        {
            if (EmailExisted(Email))
            {
                return Json("Existed Email.", JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(true, JsonRequestBehavior.AllowGet);
            }
        }

http://msdn.microsoft.com/en-us/library/gg453903(v=vs.98).aspx