Working Process of Validations in MVC5

Introduction

In this article, I am introducing the use of Data Annotations in MVC 5 using Microsoft Visual Studio 2013 Preview. As you know I previously deployed a MVC Application in which I used various types of techniques like Adding View, Adding Model, Login, CRUD Operations, Code Migration, Searching. These are very necessary in MVC Applications but when you develop applications, it is necessary to apply validations on that app. So, here you will learn how to validate an app in MVC 5.

In that context, validations are applied in MVC applications by the following assembly:

  1. using System.ComponentModel.DataAnnotations;  

Here I will tell you that I am creating validation logic in my Cricketers Model. When a user creates or edits any cricketer. You can see the validation on my page in the following image:

Validations-in-MVC5.jpg

Don't Repeat Yourself

Whenever you design an ASP.NET MVC application, Don't Repeat Yourself (DRY) is the basic assumption that you need to use. This makes your code clean, reduces the amount of code and easy to maintain because the more code you write with fewer errors the more your code functions better.

In ASP.NET MVC applications, validations are defined in the Model Class and applied all over the application. The Entity Framework Code First approach and MVC are the pillar for the validation.

So, let's begin to take advantage of Data Annotation of MVC in your application with the following criteria.

Use of Data Annotation

You need to add some logic for validation in your MVC application. For adding let's start step-by-step.

Step 1: Open Cricketers.cs from the Solution Explorer.

solutionexplorer.jpg

Step 2: Add the following assembly reference at the top of your Cricketers.cs file:

  1. using System.ComponentModel.DataAnnotations;  

Step 3: Change your code with the following code (depends on your logic):

 

  1. using System.ComponentModel.DataAnnotations;  
  2. using System.Data.Entity;  
  3. namespace MvcCricket.Models  
  4. {  
  5.     public class Cricketer  
  6.     {  
  7.         public int ID { getset; }  
  8.         [Required]  
  9.         [StringLength(50, MinimumLength=4)]  
  10.         public string Name { getset; }  
  11.         [Required]  
  12.         [Range(1,500)]  
  13.         public int ODI { getset; }  
  14.         [Required]  
  15.         [Range(1,200)]  
  16.         public int Test { getset; }  
  17.         [Required]  
  18.         public string Grade { getset; }  
  19.     }  
  20. }  

 

In the code above, you can see that the Required attribute is used in each property. That means that the user needs to enter the value in it. In the Name property the StringLength attribute defines the min and max length of the Name. In the ODI and TEST property the Range attribute is defined to min and max length.

Step 4: Open a Library Package Manager Console and write the following command in it:

add-migration DataAnnotations

After pressing Enter:

AddMigration.jpg

Step 5: Again write the following command in the Library Package Manager Console:

update-database

What does Visual Studio do? Visual Studio opens the DataAnnotations.cs file and you will see the DbMigration class is the base class of DataAnnotations. There are two methods in it. In the Up() and Down(), you will see the updated database schema. Check it out with the following code:

 

  1. namespace MvcCricket.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.     public partial class DataAnnotations : DbMigration  
  6.     {  
  7.         public override void Up()  
  8.         {  
  9.             AlterColumn("dbo.Cricketers""Name", c => c.String(nullable: false, maxLength: 50));  
  10.             AlterColumn("dbo.Cricketers""Grade", c => c.String(nullable: false));  
  11.         }  
  12.         public override void Down()  
  13.         {  
  14.             AlterColumn("dbo.Cricketers""Grade", c => c.String());  
  15.             AlterColumn("dbo.Cricketers""Name", c => c.String());  
  16.         }  
  17.     }  
  18. }  

You can see in the code above that the Name and Grade property are no longer nullable. You need to enter values in it. Code First ensures that the validation rules you specify on a model class are enforced before the application saves changes in the database.

Step 6: Debug your application and open the Cricketers folder.

HomePage.jpg

Click on Create New Link to create some new cricketer.

Validations-in-MVC5.jpg

That's It. If you want to know the working process of validation process then you to notice my following paragraph.

Validation Process

 

  1. public ActionResult Create()  
  2. {  
  3.     return View();  
  4. }  
  5. //  
  6. // POST: /Cricketers/Create  
  7. [HttpPost]  
  8. [ValidateAntiForgeryToken]  
  9. public ActionResult Create(Cricketer cricketer)  
  10. {  
  11.     if (ModelState.IsValid)  
  12.     {  
  13.         db.Cricketers.Add(cricketer);  
  14.         db.SaveChanges();  
  15.         return RedirectToAction("Index");  
  16.     }  
  17.     return View(cricketer);  
  18. }  

In the code above when the form opens in the browser the HTTP GET method is called and in the Create action method initiates. The second method HttpPost handles the post method. This method checks that the validation errors in the form and if the object finds the errors then the Create method re-creates the form, otherwise the method saves the data in the database. In here, the form is not posted to the server, because the validation error occurs in the client-side. You can also disable your JavaScript to see the error using a breakpoint.

The following is an example of that.

In Internet Explorer

IO1.jpg

IO2.jpg

In Google Chrome

gc.jpg

Validation Summary

You can also see the changes in your Create.cshtml file when you apply the Validation in your application. Check it out in my file:

 

  1. @using (Html.BeginForm())  
  2. {  
  3.     @Html.AntiForgeryToken()  
  4.     @Html.ValidationSummary(true)  
  5.     <fieldset class="form-horizontal">  
  6.         <legend>Cricketer</legend>  
  7.         <div class="control-group">  
  8.             @Html.LabelFor(model => model.Name, new { @class = "control-label" })  
  9.                      <div class="controls">  
  10.                            @Html.EditorFor(model => model.Name)  
  11.                            @Html.ValidationMessageFor(model => model.Name, nullnew { @class = "help-inline" })  
  12.                      </div>  
  13.               </div>  
  14.         <div class="control-group">  
  15.             @Html.LabelFor(model => model.ODI, new { @class = "control-label" })  
  16.                      <div class="controls">  
  17.                            @Html.EditorFor(model => model.ODI)  
  18.                            @Html.ValidationMessageFor(model => model.ODI, nullnew { @class = "help-inline" })  
  19.                      </div>  
  20.               </div>  
  21.         <div class="control-group">  
  22.             @Html.LabelFor(model => model.Test, new { @class = "control-label" })  
  23.                      <div class="controls">  
  24.                            @Html.EditorFor(model => model.Test)  
  25.                            @Html.ValidationMessageFor(model => model.Test, nullnew { @class = "help-inline" })  
  26.                      </div>  
  27.               </div>  
  28.         <div class="control-group">  
  29.             @Html.LabelFor(model => model.Grade, new { @class = "control-label" })  
  30.             <div class="controls">  
  31.                 @Html.EditorFor(model=>model.Grade)  
  32.                 @Html.ValidationMessageFor(model => model.Grade, nullnew { @class = "help-inline" })  
  33.             </div>  
  34.         </div>  
  35.         <div class="form-actions no-color">  
  36.             <input type="submit" value="Create" class="btn" />  
  37.         </div>  
  38.     </fieldset>  
  39. }   

Summary

So far this article will help you to learn to validate your MVC Application. You can also see the procedure and working procedure of Validation in my app. So just go for it.


Similar Articles