How to display an error message using ValidationSummary in ASP.NET MVC?


ValidationSummary displays a list of validation error messages for all fields. You can also display custom error messages using ValidationSummary, not related to any field.

Display Field Level Error Messages using ValidationSymmary

By default, ValidationSummary filters out field level error messages. If you want to display field level error messages as a summary, then specify excludePropertyErrors = false.

Example: ValidationSummary to Display Errors
@Html.ValidationSummary(false, "", new { @class = "text-danger" })

So now, the following Edit view will display error messages as a summary at the top. Please make sure that you don't have the ValidationMessageFor method for each field.

Display an error message using ValidationSymmary

Display Custom Error Messages

You can also display custom error message using the ValidationSummary. For example, we want to display a message if the student name already exists in the database.

To display a custom error message, first of all, you need to add custom errors into ModelState in the appropriate action method.

Example: Add Errors in ModelState
if (ModelState.IsValid) { 
              
    //check whether name is already exists in the database or not
    bool nameAlreadyExists = * check database *       
        
    if(nameAlreadyExists)
    {
        ModelState.AddModelError(string.Empty, "Student Name already exists.");
    
        return View(std);
    }
}

As you can see in the above code, we have added a custom error message using the ModelState.AddModelError() method. The ValidationSummary() method will automatically display all the error messages added in the ModelState.

Error Message in ValidationSymmary

Thus, you can use the ValidationSummary helper method to display error messages.