To use the attribute, first we need to prepare an action method:
[HttpPost] public ActionResult CheckFirstName(string firstname) { return Json(firstname.Equals("firstname")); }
Then specify the attribute on a field of a model:
[Remote("CheckFirstName", "Account", HttpMethod = "Post", ErrorMessage = "First name is not valid")] public string FirstName { get; set; }In this case we pass the action method name, controller name, HTTP method used by the action and a default error message. Notice also that the action method must accept an input parameter which would be the field's value. When specifying the Remote attribute we could also use a route name or action, controller and area names.
Let us look at another example. Here we have another action method:
[HttpPost] public ActionResult CheckFullName(string fullName, string firstname, string lastname) { return Json(fullName.Equals(string.Format("{0} {1}", firstname, lastname))); }
Then on the model class:
[Remote("CheckFullName", "Account", HttpMethod="Post", AdditionalFields="FirstName,LastName", ErrorMessage = "Full name is not valid")] public string FullName { get; set; }
This time we pass additional fields to the validation method. Notice the AdditionalFields parameter and also on the action method there are extra parameters passed.
One important thing to remember, to avoid the validation result being cached by the browser, we need to include this attribute on the controller action:
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
Reference:
The Complete Guide To Validation In ASP.NET MVC 3 - Part 1
1 comment:
A word on security here would be nice, httppost is okay. httpget could lead to some issues, data mining, cxx, leaking secure data if that is what you try to validate.
Post a Comment