Wednesday, November 9, 2011

asp.net mvc 3.0 remote attribute

asp.net mvc 3.0 remote attribute For Custom Validation on Client Side

Now a day all web application validation required to done on client side. We all are facing problem for validation limitation on client side. Because we can validate email address, credit cards on JavaScript but related to specific validation for project we can't make it there or its very complicated. So now for that Microsoft introduces new attributes Remote we can use easily in mvc 3.0 Rozer for Custom validation.

Here is my simple User information view which contain Name and city

@model MvcApplication1.Model.UserInformation

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

UserInformation
<div class="editor-label">@Html.LabelFor(model =&gt; model.Name)</div>
<div class="editor-field">@Html.EditorFor(model =&gt; model.Name)
@Html.ValidationMessageFor(model =&gt; model.Name)</div>
<div class="editor-label">@Html.LabelFor(model =&gt; model.City)</div>
<div class="editor-field">@Html.EditorFor(model =&gt; model.City)
@Html.ValidationMessageFor(model =&gt; model.City)</div>
}
<div>@Html.ActionLink("Back to List", "Index")</div>
<div>

Here is User information Model



public class UserInformation
{
[Required]
[System.Web.Mvc.Remote("IsUserNameExits", "Validation")]
public string Name { get; set; }</code>

[Required]
public string City { get; set; }

}

Now look at System.Web.Mvc.Remote Attributes where you can define custom rulers. I have create one Validation controller where i will put all custom validation Now here I explain Remote attributes in Mvc 3.0 for custom validation Look at my validation controller

public JsonResult IsUserNameExits(string Name)
{

//you can write code for check in database

if (Name == "Bhavik")
{
return Json("Sorry UserName Already Taken", JsonRequestBehavior.AllowGet);

}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}

}

Now when i type in Name textbox application will check in IsUserNameExits method for if this user exits or not so this way you can make as much validation as you want related to specific to your project and call it from client side using remote attributes

Remote Attribute Mvc3.0 asp.net mvc 3.0 remote attribute For Custom Validation on Client Side

No comments:

Post a Comment