Reader Level:
ARTICLE

Remote Attribute in MVC

On July 12, 2012 Articles | ASP.NET Programming
In this article I am try to explain how to use the Remote Attribute in MVC applications.
  • 0
  • 0
  • 6357
Download Files:
 

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:
 
First.png
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.  

public
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.
 
[Required]

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

public
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.
 
Second.jpg
 

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:
 Third.png

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

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...

  • 190rank
  • 413K readers
  • 1times
COMMENT USING

Trending up