Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

People also ask

What is HTML ValidationSummary true?

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.

Can we display all errors in one go in MVC?

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

How do I create a custom error message in ValidationSummary?

AddModelError() method. The ValidationSummary() method will automatically display all the error messages added in the ModelState . Thus, you can use the ValidationSummary helper method to display error messages.

What is ModelState AddModelError?

AddModelError(String, Exception) Adds the specified model error to the errors collection for the model-state dictionary that is associated with the specified key.


I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:

ModelState.AddModelError(string.Empty, ex.Message);

This works better, as you can show validationMessage for a specified key:

    ModelState.AddModelError("keyName","Message");

and display it like this:

    @Html.ValidationMessage("keyName")

I know this is kind of old and has been marked as answers with 147 up votes, but there is something else to consider.

You can have all the model errors, the property named and string.Empty keys alike, be shown in the ValidationSummary if you need to. There is an overload in the ValidationSummary that will do this.

    //   excludePropertyErrors:
    //   true to have the summary display model-level errors only, or false to have
    //   the summary display all errors.
    public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors);

enter image description here


Maybe like that:

[HttpPost]
public ActionResult Register(Member member)
{
    try
    {
       if (!ModelState.IsValid)
       {
          ModelState.AddModelError("keyName", "Form is not valid");
          return View();
       }
       MembersManager.RegisterMember(member);
    }
    catch (Exception ex)
    {
       ModelState.AddModelError("keyName", ex.Message);
       return View(member);
    }
}

And in display add:

<div class="alert alert-danger">
  @Html.ValidationMessage("keyName")
</div>

OR

<div class="alert alert-danger">
  @Html.ValidationSummary(false)
</div>

@Html.ValidationSummary(false,"", new { @class = "text-danger" })

Using this line may be helpful