2
votes

As far as I know asp-validation-summary could be one of the following:

  • None
  • ModelOnly
  • All

I'm wondering if there is any possible way or trick to get all NonModel errors or in other words all erros added via ModelState.AddModelError("custom", "some error who doesn't come from ValidationAttribute in the Model");

3

3 Answers

3
votes

No, because there's no meaningful distinction between the two. ModelState is a dictionary of enumerable strings. There's no information about where a particular key or value or item in that value came from.

"Model" errors are simply errors added to the empty string key, wherease "non-model" errors are anything else. That's all you've got.

2
votes

Faced with the same problem. I want to display field errors in-place, and server-side errors in Bootstrap alert. To distinguish explicitly added errors I add them with prefix ("#" in my case):

ModelState.AddModelError("#SomeError", "Some error occured");

Then these errors can be filtered in the view/page this way:

    var explicitlyAddedErrors = Model
        .Where(_ => _.Key.StartsWith("#"))
        .SelectMany(_ => _.Value.Errors)
        .ToList();

Hope this will be useful for somebody. :)

0
votes

You can add the following line to where you'd normally put asp-validation-summary

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

First parameter determines whether to exclude Property Errors. Since I already have asp-validation-for = "PROPERTY", I leave mine as true; no point in displaying the same error message multiple times.

Second parameter is to display a header for the error message. For example:

@Html.ValidationSummary(true, "Errors", new { @class = "text-danger" })
Errors
 * Invalid Login

"Errors" will only show if there is at least one error.

Last parameter is self explanatory.

Hope this helps! :)