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:
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:
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.
Step 2: Add the following assembly reference at the top of your Cricketers.cs file:
using System.ComponentModel.DataAnnotations;
Step 3: Change your code with the following code (depends on your logic):
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
namespace MvcCricket.Models
{
public class Cricketer
{
public int ID { get; set; }
[Required]
[StringLength(50, MinimumLength=4)]
public string Name { get; set; }
[Required]
[Range(1,500)]
public int ODI { get; set; }
[Required]
[Range(1,200)]
public int Test { get; set; }
[Required]
public string Grade { get; set; }
}
}
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:
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:
namespace MvcCricket.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class DataAnnotations : DbMigration
{
public override void Up()
{
AlterColumn("dbo.Cricketers", "Name", c => c.String(nullable: false, maxLength: 50));
AlterColumn("dbo.Cricketers", "Grade", c => c.String(nullable: false));
}
public override void Down()
{
AlterColumn("dbo.Cricketers", "Grade", c => c.String());
AlterColumn("dbo.Cricketers", "Name", c => c.String());
}
}
}
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.
Click on Create New Link to create some new cricketer.
That's It. If you want to know the working process of validation process then you to notice my following paragraph.
Validation Process
public ActionResult Create()
{
return View();
}
//
// POST: /Cricketers/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Cricketer cricketer)
{
if (ModelState.IsValid)
{
db.Cricketers.Add(cricketer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(cricketer);
}
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
In Google Chrome
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:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset class="form-horizontal">
<legend>Cricketer</legend>
<div class="control-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name, null, new { @class = "help-inline" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(model => model.ODI, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model => model.ODI)
@Html.ValidationMessageFor(model => model.ODI, null, new { @class = "help-inline" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(model => model.Test, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model => model.Test)
@Html.ValidationMessageFor(model => model.Test, null, new { @class = "help-inline" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(model => model.Grade, new { @class = "control-label" })
<div class="controls">
@Html.EditorFor(model=>model.Grade)
@Html.ValidationMessageFor(model => model.Grade, null, new { @class = "help-inline" })
</div>
</div>
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn" />
</div>
</fieldset>
}
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.