Understanding Validation in MVC - Part 2

This article is continuation of previous article,

This article focuses on implementing remote validation is MVC.

Remote Validation

This server side validation helps to call the server action to validate the data. Remote validation helps to validate the data without posting entire form to the server. For example, validating user name. User Name we cannot validate i.e. check is already exist in the database unless we hit the database. And posting whole page for just validating user name hits the performance. So just post user name part to the method and validate it.

We have the following steps to implement it

Step 1: Define Action in the controller. Define the action in controller and post the data to validate. Return the result true or false in JSON format.

Check in my action in the following example. I am verifying that email id already exist.

  1. [HttpPost]  
  2. public JsonResult IsValidEmailIdExits(FormCollection parm)  
  3. {  
  4.    string SelectedStudent_Email = System.Convert.ToString(parm[0]);  
  5.    var objStudentDetailsModel = new StudentDetailsModel();  
  6.    // Your Database Search call   
  7.    var strudentList = objStudentDetailsModel.GetStudentList();  
  8.    return Json(!strudentList.Any(x => x.Email == SelectedStudent_Email),JsonRequestBehavior.AllowGet);  
  9. }  
Step 2: Apply the remote attribute mention controller and action in it. Also specify HttpMethod = Post and error message

remote attribute mention controller

Step 3: Finally validate the controller,

validate the controller

Step 4: Execute the project you will find your only action will get call without whole page post back.

Output

Please go through the project attached, which will help you to understand in more detail.

I hope you understood how remote validations is performed in MVC. In the next article we will see rest of the things in validation, such as Custom Validation and Validation Summary.