Display validation error messages in ASP.NET MVC

Introduction


In order to display a validation error message for a specified field in ASP.NET MVC, we use the html helper: ValidationMessageFor.

ValidationMessageFor Usage


Following is a student entity that has the Required data annotation associated with two properties: the first name and the last name of a student.

public class Student
{
    public int StudentId { get; set; }

    [Required (ErrorMessage = "The field 'First Name' is required")]
    public string firstName { get; set; }

    [Required (ErrorMessage = "The field 'Last Name' is required")]
    public string lastName { get; set; }

    public int age { get; set; }
}

As an example, we want to add a student via an HTML form and we want to force the user to enter the first name of the student.

Below is the code for displaying an error message in case the user didn't enter a value for the student's first name:

@Html.TextBoxFor(m => m.firstName) <br />
@Html.ValidationMessageFor(m => m.firstName)

We pass a lambda expression of the first name property as a parameter of the ValidationMessageFor method. If the user don't enter a value for the student's first name, he will get the following errer message: The field 'First Name' is required

See also