ASP.NET MVC: ValidationSummary

The ValidationSummary() extension method displays a summary of all validation errors on a web page as an unordered list element. It can also be used to display custom error messages.

The ValidationMessageFor displays an error message for an individual field, whereas the ValidationSummary displays all the error messages.

Consider the following Student model class with the Required and Range validation attributes.

Example: Student Model
public class Student
{
    public int StudentId { get; set; }
    [Required]
    public string StudentName { get; set; }
    [Range(10, 20)]
    public int Age { get; set; }
}

The following view uses the ValidationSummary() method to display all the error messages.

Example: ValidationMessageFor
@model Student  
@Html.ValidationSummary(false, "", new { @class = "text-danger" })

@Html.HiddenFor(model => model.StudentId)    

@Html.EditorFor(m => m.StudentName) <br />
@Html.EditorFor(m => m.Age) <br />

Above, the first parameter of the ValidationSummary() is false, so it will display the field level errors as a summary. The second parameter is for the message. We don't want to provide a message there so specify an empty string. The third parameter is for HTML attributes such as CSS class for messages. The above will display the error messages as a summary shown below.

ValidationSummary Error Message

Display Custom Error Messages

You can also display a custom error message using ValidationSummary.

Here, we will display a message if a student's name already exists in the database. So, in the HTTP Post action method, check the name in the database and add error message in the ModelState dictionary if the name already exists, as shown below.

Example: Edit Action methods:
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
            
            //check whether name is already exists in the database or not
            bool nameAlreadyExists = * check database *       
        
            if(nameAlreadyExists)
            {
                //adding error message to ModelState
                ModelState.AddModelError("name", "Student Name Already Exists.");
    
                return View(std);
            }
            
            return RedirectToAction("Index");
        }

        return View(std);
    }
}

Above, we added a custom error message using the ModelState.AddModelError() method. The ValidationSummary() method will automatically display all the error messages added into the ModelState.

Custom Error Message in ValidationSummary