w3resource

ASP.NET MVC-ValidationSummary


In the previous tutorials, we learnt about ValidationMessage and ValidationMessageFor helper functions used to display error messages from in an ASP.NET MVC project.

In this tutorial, we will discuss the ValidationSummary helper method, which generates an unordered list of validation messages from the ModelStateDictionary object.

The ValidationSummary is used to display all the error messages from all the form fields. It can also be used to display custom error messages.

ValidationSummary() Signature

MvcHtmlString ValidateMessage(bool excludePropertyErrors, string message, object htmlAttributes)

The ValidationSummary() have several overloads, just like every normal method in C#. For a comprehensive overloads of ValidationSummary() helper method, visit the MSDN website.

Displaying Field Error Messages using ValidationSummary

ValidationSummary by default, filters out field level error messages. But if you want to display field level error messages as a summary then, you must specify excludePropertyErrors = false as illustrated in the code snippet below.

//Example: ValidationSummary to display field errors
@Html.ValidationSummary(false, "", new {@class = "text-danger"})

With the above code snippet on an ASP.NET edit view, error messages will be displayed as a summary on top of the form.

To avoid conflicts, don?t include ValidationSummary and ValidationMessageFor on the same form filed.

Display Custom Error Messages

You can also display a custom error message using ValidationSummary. For example, we want to display a message if there is a duplicate Activity Name.

To show a custom error message, we must add custom errors into the ModelState in the appropriate action method.

//Example: Add error 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, "Activity Name has already been recoded");
        return View();
    }
}

From the above code snippet, we have added custom error messages using the ModelState.AddModelError method. The ValidationSummary method in the view will automatically display all the error messages added into the ModelState.

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



Inviting useful, relevant, well-written and unique guest posts