Friday, October 18, 2019

What is the use of remote validation in MVC?

Remote validation is the process where we validate specific data posting data to a server without posting the entire form data to the server. Let's see an actual scenario, in one of my projects I had a requirement to validate an email address, whetehr it already exists in the database. Remote validation was useful for that; without posting all the data we can validate only the email address supplied by the user.

Practical Explanation
Let's create a MVC project and name it accordingly, for me its “TestingRemoteValidation”. Once the project is created let's create a model named UserModel that will look like:
  1. public class UserModel   
  2. {  
  3.     [Required]  
  4.     public string UserName   
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     [Remote("CheckExistingEmail""Home", ErrorMessage = "Email already exists!")]  
  10.     public string UserEmailAddress  
  11.     {  
  12.         get;  
  13.         set;  
  14.     }  
  15. }  
Let's get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the the name of the action. The second parameter “Home” is referred to as controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the “Home” controller is called and the third parameter is the error message. Let's implement the “CheckExistingEmail” action result in our home controller.
  1. public ActionResult CheckExistingEmail(string UserEmailAddress)  
  2. {  
  3.     bool ifEmailExist = false;  
  4.     try  
  5.     {  
  6.         ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com") ? true : false;  
  7.         return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);  
  8.     } catch (Exception ex)  
  9.     {  
  10.         return Json(false, JsonRequestBehavior.AllowGet);  
  11.     }  
  12. }  

No comments:

Post a Comment

Get max value for identity column without a table scan

  You can use   IDENT_CURRENT   to look up the last identity value to be inserted, e.g. IDENT_CURRENT( 'MyTable' ) However, be caut...