ASP.NET MVC includes built-in attribute classes in the System.ComponentModel.DataAnnotations namespace. These attributes are used to define metadata for ASP.NET MVC and ASP.NET data controls. You can apply these attributes to the properties of the model class to display appropriate validation messages to the users.
The following table lists all the data annotation attributes which can be used for validation.
Let's see how to use these attributes to display validation messages on the view.
The following is the Student model class.
Example: Apply DataAnnotation Attributes
public class Student
{
public int StudentId { get; set; }
public string StudentName { get; set; }
public int Age { get; set; }
}
We want to implement validations for StudentName and Age property values. We want to make sure that users do not save empty StudentName or Age value. Also, age should be between 10 to 20.
The Required attribute is used to specify that the value cannot be empty. The Range attribute is used to specify the range of values a property can have. We will use the Required attribute on the StudentName to make it mandatory for the user to provide value and Range attribute to make sure the user enters value between 10 to 20, as shown below.
Example: Apply DataAnnotation Attributes
public class Student
{
public int StudentId { get; set; }
[Required]
public string StudentName { get; set; }
[Range(10, 20)]
public int Age { get; set; }
}
The above attributes define the metadata for the validations of the Student class. This alone is not enough for the validation. You need to check whether the submitted data is valid or not in the controller. In other words, you need to check the model state.
Use the ModelState.IsValid to check whether the submitted model object satisfies the requirement specified by all the data annotation attributes. The following POST action method checks the model state before saving data.
Example: Edit Action methods:
Copy
public class StudentController : Controller
{
public ActionResult Edit(int id)
{
var stud = ... get the data from the DB using Entity Framework
return View(stud);
}
[HttpPost]
public ActionResult Edit(Student std)
{
if (ModelState.IsValid) { //checking model state
//update student to db
return RedirectToAction("Index");
}
return View(std);
}
}
Now, create an edit view as shown here
. The following is a generated edit view using the default scaffolding template.
Edit View: Edit.cshtml
Copy
@model MVC_BasicTutorials.Models.Student
@{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
In the above view, it calls the HTML Helper method ValidationMessageFor() for every field and ValidationSummary() method at the top. The ValidationMessageFor() displays an error message for the specified field. The ValidationSummary() displays a list of all the error messages for all the fields.
In this way, you can display the default validation message when you submit a form without entering StudentName or Age, as shown below.
Validation
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (