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.
- [HttpPost]
- public JsonResult IsValidEmailIdExits(FormCollection parm)
- {
- string SelectedStudent_Email = System.Convert.ToString(parm[0]);
- var objStudentDetailsModel = new StudentDetailsModel();
-
- var strudentList = objStudentDetailsModel.GetStudentList();
- return Json(!strudentList.Any(x => x.Email == SelectedStudent_Email),JsonRequestBehavior.AllowGet);
- }
Step 2: Apply the remote attribute mention controller and action in it. Also specify HttpMethod = Post and error message
Step 3: Finally validate the controller,
Step 4: Execute the project you will find your only action will get call without whole page post back.
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.