Reader Level:

Remote Attribute in MVC

By Amit Patel on Jul 12, 2012
In this article I am try to explain how to use the Remote Attribute in MVC applications.

ASP.NET MVC 3 provides a mechanism that can make a remote server call to validate a form field without posting the entire form to the server. This is useful when you have a field that cannot be validated on the client and is therefore likely to fail validation when the form is submitted.

In this attribute I am try to explain how we can use the Remote Attribute in a MVC application.
Step 1: We'll create a new MVC application in Visual Studio:
Step 2: Now to open the AccountController.cs file and add a new method there. 
If the username contains "abc" it means the username is a duplicate. You can write your own logic to check the username.  

JsonResult CheckDuplicateUserName(string UserName)

    if (UserName.Contains("abc"))
        return Json("Username is already exist", JsonRequestBehavior.AllowGet);
    return Json(true, JsonRequestBehavior.AllowGet);


The above method will return the Json object.
Step 3: Now in the RegisterModel class we will add a Remote attribute for the Username Property.

[Display(Name ="User name")]
[Remote("CheckDuplicateUserName","Account", "", ErrorMessage = "Dupicate")]

string UserName { get; set; } 

In the following image, the first parameter is action and the second parameter is controller and the other parameters are optional.

Step 4: Now we will run our application and navigate to the Register page. If you try with another value like xyz then it will not give you an error:

You can also download the source code for this article.
Happy Coding.

Amit Patel
Amit Patel

I am  C# Corner MVP in Q2 2012.  I have 10 years of experiences in Microsoft technologies. I am very much passionate about Web technology. My core skill is ASP.NET, WCF, C#, JQuery and CSS.



Spire.Doc - Free .NET Word API
Use Spire.Doc to create, read, write, print, and convert word documents to OpenXML, RTF, TXT, XPS, EPUB, EMF, HTML, Image and PDF.

Trending up

Infragistics jQuery Controls