Monday, January 9, 2012

Asynchronous Remote validation in MVC3 with razor

In many website you found that when you registering at that time username validate asynchronously while you filling other details without posting page back and that's look awesome!.
I would like to share same scenario using MVC3, hope you know about MVC before reading further. In MVC you have to handle all validation from model.
Now i came to point , just i have register page where first field is username as per below in index.cshtml under Wizard folder.


<div class="editor-label">
  @Html.LabelFor(model=> model.UserName)
div>

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


In Model wizard.cs following validation


[Required(ErrorMessage= "Full Name required.")]
[StringLength(20,ErrorMessage = "Username must be under 20 chars.")]
public string UserName { get;set;}


Now just add remote validation as per below In this example, we are going to add remote validation to the username field to check that it is unique.


[Remote("ValidateUsername","Wizard",HttpMethod = "POST",ErrorMessage = "username is not available")]
Remote has three constructors allow you to specify either 
-RouteName, 
-Controller and action or 
-Controller, action and area. 
Here we are passing controller and action and additionally overriding the error message.


Now define action in wizardcontroller.cs as per below


public ActionResult ValidateUsername(string username)
{
return Json(!username.ToLower().Equals("duplicate"),JsonRequestBehavior.DenyGet);
}


here for sake of simplicity i have just validate username with duplicate string and return rue or false based on that , in real scenario database validation logic goes here. 


Now when you test it browser and inspect with firbug then you can able to watch asynchronous post request when you are typing in username textbox or leaving focus from that as per below .

read more about JsonRequestBehavior enumeration
here

if you 
want to pass additional field then change code as per below
[Remote("ValidateUsername","Wizard",HttpMethod = "POST",AdditionalFields="Email",
ErrorMessage = "username is not available")]
public ActionResult ValidateUsername(string username , string email)
{
//put some validation involving username and email here
return Json(!username.ToLower().Equals("duplicate"),JsonRequestBehavior.DenyGet);
}


Related Links

No comments: