I hope the above articles are clear. So we will move ahead and get hands on with Data Annotations in ASP.NET MVC.
It is very easy to use and the code becomes much cleaner as compared to normal ASP.NET validators.
Let us understand some of the validator attributes that we can use in MVC.
Types of Data Annotations in ASP.NET MVC
Required
This attribute specifies that the value is mandatory and cannot be skipped.
Syntax
[Required(ErrorMessage="Please enter name"),MaxLength(30)]
DataType
This attribute is used to specify the datatype of the model.
Syntax
[DataType(DataType.Text)]
Range
Using this attribute we can set a range between two numbers.
Syntax
[Range(100,500,ErrorMessage="Please enter correct value")]
StringLength
Using this attribute we can specify maximum and minimum length of the property.
Syntax
[StringLength(30,ErrorMessage="Do not enter more than 30 characters")]
DisplayName
Using this attribute we can specify property name to be displayed on view.
Syntax
[Display(Name="Student Name")]
MaxLength
Using this attribute we can specify maximum length of property.
Syntax
[MaxLength(3)]
Bind
This attribute specifies fields to include or exclude for model binding.
Syntax
[Bind(Exclude = "StudentID")]
DisplayFormat
This attribute allows us to set date in the format specified as per the attribute.
Syntax
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
RegularExpression
We can set a regex pattern for the property. For ex: Email ID.
Syntax
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]
Creating MVC Application
Let us implement these in a sample application. Open Visual Studio. Go to File->New->Project. Give a suitable name to the application. Click OK.
Select MVC Template. Click OK.
Adding Model to Application.
Let us create a model in the Models folder. I have named it Student.
Add the following properties to it.
public class Student
[ScaffoldColumn(false)]
publicintStudentID { get; set; }
[DataType(DataType.Text)]
[Required(ErrorMessage = "Please enter name"), MaxLength(30)]
[Display(Name = "Student Name")]
public string Name { get; set; }
[MaxLength(3),MinLength(1)]
[Required(ErrorMessage = "Please enter marks")]
publicint Marks { get; set; }
[DataType(DataType.EmailAddress)]
[Required(ErrorMessage = "Please enter Email ID")]
[RegularExpression(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$", ErrorMessage = "Email is not valid.")]
public string Email { get; set; }
[Required(ErrorMessage = "Please enter department")]
public string Department { get; set; }
[Required(ErrorMessage = "Please enter Mobile No")]
[Display(Name = "Contact Number")]
[DataType(DataType.PhoneNumber)]
public int Mobile { get; set; }
}
Let us create a context class now. Add the following method in the class.
public class StudentsDbcontext : DbContext
{
publicDbSet<Student> Students { get; set; }
}
To import DbContext we need to include using System.Data.Entity namespace in the application.
So our final model is complete,
Adding Controller
Let us add controller. Right click on Controller. Add->Controller.
Select MVC 5 Empty Controller. Click Add. I have named it Student.
We have the following method in controller.
public ActionResult Index()
{
return View();
}
Adding View
Let us add a view for this ActionResult. Right click on Index() method. Go to Add->View. Select the Create template as we wish to create an input form. We will select Student as Model Class as we have created this model and finally we need to select our context class that we have created along with our model. Click Add.
We should get a view view the following markup.
@modelDataAnnotations.Models.Student
@{
ViewBag.Title = "Index";
}
<h2>Using Data Annotations</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4></h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model =>model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model =>model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model =>model.Marks, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model =>model.Marks, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>model.Marks, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model =>model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model =>model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model =>model.Department, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model =>model.Department, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>model.Department, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model =>model.Mobile, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model =>model.Mobile, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model =>model.Mobile, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btnbtn-primary" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@sectionScripts {
@Scripts.Render("~/bundles/jqueryval")
}
Browse the Application
Let us now run the application and check if validations are working.
So we have validations working perfectly. Further we will be validating our model to test other specified validations also.
Summary
So we have successfully implemented Data annotations in ASP.NET MVC application. I hope this post is useful to developers.