Thursday 17 May 2012

Using Remote Attribute Validator in ASP.NET MVC 3

In the past I have written a few posts about validation in ASP.NET MVC 3. One of them is about creating custom client side validation. There is another way to do client validation in MVC 3. This one is easier to implement for standard/common validation functions. It is the new RemoteAttribute. This attribute allows us to have client side validation that calls controller action on the back end.

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:

Anonymous said...

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.