Remote Validation In ASP.NET MVC

Background

Many times, we need to check instantly whether a record already exists in the database or not. For example, at the time of signup, we need to check if the user is already registered with current Email id, or the username is already taken. So, to achieve these functionalities, there are many methods, but in ASP.NET MVC, there is a very easy way to achieve these types of functionalities, i.e. with the help of remote attributes. Let's learn step by step how to check user instantly, using remote attribute in ASP.NET MVC.
 
Remote Validation in ASP.NET MVC
 
Remote is the attribute for validation in Data Annotation, which is used in model class to validate records instantly. Let's demonstrate the aforementioned concept by creating sample ASP.NET MVC application.
 
Step 1 - Create an MVC Application

Now, let us start with a step-by-step approach from the creation of a simple MVC application.

  1. Go to "Start", followed by "All Programs" and select "Microsoft Visual Studio 2015".

  2. Click "File", followed by "New" and click "Project". Select "ASP.NET Web Application Template", provide the Project a name of your choice and click OK. After clicking, the following window will appear.

    NEW

Step 2 - Create Model Class

Now, let us create the model class, named RegisterModel.cs, by right clicking on Models folder, as shown in the screenshot.
 
 

After creating the class, write the following properties in RegisterModel.cs class.
 
RegisterModel.cs
  1. using System.ComponentModel.DataAnnotations;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace RemoteValiDationInMVC.Models  
  5. {  
  6.     public class RegisterModel  
  7.     {  
  8.           
  9.         [Required]  
  10.         [DataType(DataType.EmailAddress)]  
  11.         [Display(Name ="Enter EmailId")]  
  12.         //Using Remote validation attribute   
  13.         [Remote("IsAlreadySigned""Register",HttpMethod ="POST", ErrorMessage = "EmailId already exists in database.")]  
  14.         public string UserEmailId { getset; }  
  15.         [Required]  
  16.         public string Designation { getset; }  
  17.                  
  18.         [Required]  
  19.         [DataType(DataType.Password)]  
  20.         [Display(Name =("Choose Password"))]  
  21.         public string PassWord { getset; }  
  22.   
  23.     }  

In the preceding code, we have used Remote attribute for UserEmaiId model class method with some properties which are explained below. 
 
In the above image, we have defined a few properties of Remote attribute to work on remote validation properly, let's know them in brief.
  • IsAlreadySigned 

    This is the JsonResult method which checks the details from database and returns true or false.

  • Register 

    This is MVC Controller name and inside that, IsAlreadySigned JsonResult method is defined to check the details from database.

  • HttpMethod 

    This is HttpMethod type which is called on Remote attribute e.g. Get , Put , Post. This is optional to define.

  • ErrorMessage 

    This is used to show the message at client side. 
There are many optional properties of Remote attribute which are used as per the validation requirements.
 
Step 3 - Add Controller Class
 
Now, let us add the MVC 5 Controller, as in the following screenshot.

 
After clicking on Add button, it will show the window. Specify the Controller name as Register with suffix Controller. Now, modify the default code in RegisterController.cs class file and create JsonResult method. After modifying, the code will look like as follows.

RegisterController.cs
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4. using RemoteValiDationInMVC.Models;  
  5.   
  6. namespace RemoteValiDationInMVC.Controllers  
  7. {  
  8.     public class RegisterController : Controller  
  9.     {  
  10.         // GET: Register  
  11.         [HttpGet]  
  12.         public ActionResult SignUp()  
  13.         {  
  14.             return View();  
  15.         }  
  16.         [HttpPost]  
  17.         public ActionResult SignUp(RegisterModel ObjModel )  
  18.         {  
  19.             if (ModelState.IsValid)  
  20.             {  
  21.   
  22.                 return View();  
  23.   
  24.             }  
  25.             else  
  26.             {  
  27.   
  28.                 return View();  
  29.   
  30.             }  
  31.   
  32.         }  
  33.         [HttpPost]  
  34.         public JsonResult IsAlreadySigned(string UserEmailId)  
  35.         {  
  36.               
  37.             return Json(IsUserAvailable(UserEmailId));  
  38.   
  39.         }  
  40.         public bool IsUserAvailable(string EmailId)  
  41.         {  
  42.             // Assume these details coming from database  
  43.         List<RegisterModel> RegisterUsers = new List<RegisterModel>()  
  44.         {  
  45.   
  46.             new RegisterModel {UserEmailId="[email protected]" ,PassWord="compilemode",Designation="SE"},  
  47.             new RegisterModel {UserEmailId="[email protected]" ,PassWord="abc123",Designation="Software Dev"}  
  48.   
  49.         };  
  50.             var RegEmailId = (from u in RegisterUsers  
  51.                               where u.UserEmailId.ToUpper() == EmailId.ToUpper()  
  52.                               select new { EmailId }).FirstOrDefault();  
  53.   
  54.             bool status;  
  55.             if (RegEmailId!=null)  
  56.             {  
  57.                 //Already registered  
  58.                 status = false;  
  59.             }  
  60.             else  
  61.             {  
  62.                 //Available to use  
  63.                 status = true;  
  64.             }  
  65.               
  66.   
  67.             return status;  
  68.       }  
  69.   
  70.           
  71.     }  
  72.   

Note

In the preceding code, IsAlreadySigned returns the JSON data at client side and it takes the UserEmailId as input parameter, the name of which, must match with the get set property defined under the remote attribute.
 
Step 4 - Create View

Now, let's create StronglyTyped View named SignUp from RegisterModel class.

 

Click on Add button. It will create the View named SignUp.
 
Now, open the SignUp.cshtml View. You will see some default code which is generated by MVC scaffolding template. Let's now, modify the default code to make as per our requirement.
 
SignUp.cshtml
  1. @model RemoteValiDationInMVC.Models.RegisterModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "SignUp";  
  5. }  
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.   
  10.     <div class="form-horizontal">  
  11.   
  12.         <hr />  
  13.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  14.         <div class="form-group">  
  15.             @Html.LabelFor(model => model.UserEmailId, htmlAttributes: new { @class = "control-label col-md-2" })  
  16.             <div class="col-md-10">  
  17.                 @Html.EditorFor(model => model.UserEmailId, new { htmlAttributes = new { @class = "form-control" } })  
  18.                 @Html.ValidationMessageFor(model => model.UserEmailId, "", new { @class = "text-danger" })  
  19.             </div>  
  20.         </div>  
  21.   
  22.         <div class="form-group">  
  23.             @Html.LabelFor(model => model.Designation, htmlAttributes: new { @class = "control-label col-md-2" })  
  24.             <div class="col-md-10">  
  25.                 @Html.EditorFor(model => model.Designation, new { htmlAttributes = new { @class = "form-control" } })  
  26.                 @Html.ValidationMessageFor(model => model.Designation, "", new { @class = "text-danger" })  
  27.             </div>  
  28.         </div>  
  29.   
  30.         <div class="form-group">  
  31.             @Html.LabelFor(model => model.PassWord, htmlAttributes: new { @class = "control-label col-md-2" })  
  32.             <div class="col-md-10">  
  33.                 @Html.EditorFor(model => model.PassWord, new { htmlAttributes = new { @class = "form-control" } })  
  34.                 @Html.ValidationMessageFor(model => model.PassWord, "", new { @class = "text-danger" })  
  35.             </div>  
  36.         </div>  
  37.   
  38.         <div class="form-group">  
  39.             <div class="col-md-offset-2 col-md-10">  
  40.                 <input type="submit" value="SignUp" class="btn btn-primary" />  
  41.             </div>  
  42.         </div>  
  43.     </div>  
  44. }  
  45.   
  46. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  47. <script src="~/Scripts/jquery.validate.min.js"></script>  
  48. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script> 
After adding the Model, add View and Controller into our project, the Solution Explorer will look like the following.
 
 
 
Step - 5

Now, run the application and type emaild id which is already in the  list that we defined in the RegisterController class.
 
 
Now, without posting the form, it's showing instantly that the given email id already exists in the database, This approach will save a lot of time for the user in unnecessary validation.
 
Note
  • Download the Zip file of the sample application for a better understanding.
  • Since this is a demo, it might not be using proper standards. So, improve it as per your own skills.
Summary

I hope this article is useful for all readers. If you have any suggestions, please contact me.

Read more articles on ASP.NET


Similar Articles