Remote Validation in MVC 4

Remote validation is a process where we make server calls to validate data without posting an entire form to the server. Now I will explain you step-by-step using a MVC4 application that I have used in the current project.

Let's see step-by-step.

Step 1

First we will create a database table tbl_customer.

database table

Step 2

Create a Visual Studio new project.

new project

Go to File, then New and select Project ASP.NET MVC4 Application and name it “RemoteValidation”. Then select a template, here I am selecting an internet template.

Step 3

We map the database table using Entity Framework.

Step 4

Create a model class CustomerModel.cs.

  1. public class CustomerModel  
  2. {  
  3.     public int id { getset; }  
  4.     [Required(ErrorMessage = "First Name is required")]  
  5.     public string FirstName { getset; }  
  6.     public string LastName { getset; }  
  7.     [Required(ErrorMessage = "Address is required")]  
  8.     public string Address { getset; }  
  9.     [Required(ErrorMessage = "Contact Number is required")]  
  10.     public string ContactNo { getset; }  
  11.     [Remote("ValidationForWeekEnds""Customer")]  
  12.     public string BookingDate { getset; }  
  13. }  
In BookingDate you can see remote validation,we decorate it from with the remote keyword and the name of the method and controller. We will write code for the method ValidationForWeekEnds.

Remote validation uses System.Web.Mvc or System.Web.Mvc.Remote.

Step 5

Create a Controller. I created a CustomerController.

The Customer controller contains two action methods.

The first Action method is “Index”.
  1. [HttpGet]  
  2. public ActionResult Index()  
  3. {  
  4.    return View();  
  5. }  
This method will return a view so first we will create a view, then we will come again to the controller's other method.

Step 6

We will create a view for index method.
  1. @model RemoteValidation.Models.CustomerModel  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  7. <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">  
  8. <script src="http://code.jquery.com/jquery-1.10.2.js"></script>  
  9. <script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>  
  10. <script>  
  11.     $(function () {  
  12.         $("#BookingDate").datepicker();  
  13.     });  
  14. </script>  
  15. <h2>Index</h2>  
  16. @using (Html.BeginForm())  
  17. {  
  18.     @Html.AntiForgeryToken()  
  19.     @Html.ValidationSummary(true)  
  20.   
  21.     <fieldset>  
  22.         <legend>CustomerModel</legend>  
  23.   
  24.         <div class="editor-label">  
  25.             @Html.LabelFor(x => x.FirstName)  
  26.         </div>  
  27.         <div class="editor-field">  
  28.             @Html.TextBoxFor(x => x.FirstName,new { @maxlength="50"})  
  29.             @Html.ValidationMessageFor(x => x.FirstName)  
  30.         </div>  
  31.   
  32.         <div class="editor-label">  
  33.             @Html.LabelFor(x => x.LastName)  
  34.         </div>  
  35.         <div class="editor-field">  
  36.            @Html.TextBoxFor(x => x.LastName,new { @maxlength="50"})  
  37.         </div>  
  38.   
  39.         <div class="editor-label">  
  40.             @Html.LabelFor(x => x.Address)  
  41.         </div>  
  42.         <div class="editor-field">  
  43.             @Html.TextBoxFor(x => x.Address,new { @maxlength="50"})  
  44.             @Html.ValidationMessageFor(x=> x.Address)  
  45.         </div>  
  46.   
  47.         <div class="editor-label">  
  48.             @Html.LabelFor(x=> x.ContactNo)  
  49.         </div>  
  50.         <div class="editor-field">  
  51.             @Html.TextBoxFor(x => x.ContactNo,new { @maxlength="50"})  
  52.             @Html.ValidationMessageFor(x=> x.ContactNo)  
  53.         </div>  
  54.   
  55.         <div class="editor-label">  
  56.             @Html.LabelFor(x => x.BookingDate)  
  57.         </div>  
  58.         <div class="editor-field">  
  59.             @Html.TextBoxFor(x => x.BookingDate,new { @maxlength="50"})           
  60.             @Html.ValidationMessageFor(x => x.BookingDate)  
  61.         </div>  
  62.   
  63.         <p>  
  64.             <input type="submit" value="Create" />  
  65.         </p>  
  66.     </fieldset>  
  67. }  
  68.   
  69. @section Scripts {  
  70.     @Scripts.Render("~/bundles/jqueryval")  
  71. }  
Step 7

We create a post method index and write code to insert customer information.
  1. [HttpPost]  
  2. public ActionResult Index(CustomerModel custModel)  
  3. {  
  4.     using (CCNEntities db=new CCNEntities())  
  5.     {  
  6.         tbl_customer tblCustomer = (custModel.id == 0) ? new tbl_customer() : db.tbl_customer.Where(x => x.id == custModel.id).FirstOrDefault();  
  7.         tblCustomer.FirstName = custModel.FirstName;  
  8.         tblCustomer.LastName = custModel.LastName;  
  9.         tblCustomer.Address = custModel.Address;  
  10.         tblCustomer.ContactNo = custModel.ContactNo;  
  11.         tblCustomer.BookingDate = custModel.BookingDate.ToString();  
  12.         if (custModel.id== 0)  
  13.         {  
  14.             db.tbl_customer.Add(tblCustomer);  
  15.         }  
  16.         db.SaveChanges();  
  17.     }  
  18.     return RedirectToAction("Index");  
  19. }  
Step 8

Create a method that contains the logic for remote validation. Here I am validating Booking (for example, any service provided by company) is not allowed at weekends.
  1. public JsonResult ValidationForWeekEnds(CustomerModel custModel)  
  2. {  
  3.     DateTime dt =Convert.ToDateTime(custModel.BookingDate);  
  4.     custModel.BookingDate=dt.DayOfWeek.ToString();  
  5.     if (custModel.BookingDate.Contains("Saturday") || custModel.BookingDate.Contains("Sunday"))  
  6.     {  
  7.         return Json("We do not allow booking at Weekends", JsonRequestBehavior.AllowGet);  
  8.     }  
  9.       
  10.     return Json(true, JsonRequestBehavior.AllowGet);  
  11. }  
Step 9

Finally run the application and see if we select a BookingDate from the date picker. If the day is Sunday or Saturday, then it will validate without posting an entire form to the server.

index

I hope you will like it.

 

Up Next
    Ebook Download
    View all
    Learn
    View all