How to get all errors from ASP.Net MVC modelState?

I want to get all the error messages from modelstate without knowing the key value. Loop to get all the error messages contained in the modelstate.

How can I do that?

#1 building

It also works:

var query = from state in ModelState.Values
    from error in state.Errors
    select error.ErrorMessage;
var errors = query.ToArray(); // ToList() and so on...

#2 building

In addition, ModelState.Values.ErrorMessage may be empty, but ModelState.Values.Exception.Message may indicate an error.

#3 building

foreach (ModelState modelState in ViewData.ModelState.Values) {
    foreach (ModelError error in modelState.Errors) {
        DoSomethingWith(error);
    }
}

See also How to get the collection of model state errors in ASP.NET MVC? .

#4 building

I can do this with a little LINQ,

public static List<string> GetErrorListFromModelState
                                              (ModelStateDictionary modelState)
{
      var query = from state in modelState.Values
                  from error in state.Errors
                  select error.ErrorMessage;

      var errorList = query.ToList();
      return errorList;
}

The above method returns a list of validation errors.

Read more:

How to read all errors from ModelState in ASP.NET MVC

#5 building

During debugging, I found it useful to place a table at the bottom of each page to display all ModelState errors.

<table class="model-state">
    @foreach (var item in ViewContext.ViewData.ModelState) 
    {
        if (item.Value.Errors.Any())
        { 
        <tr>
            <td><b>@item.Key</b></td>
            <td>@((item.Value == null || item.Value.Value == null) ? "<null>" : item.Value.Value.RawValue)</td>
            <td>@(string.Join("; ", item.Value.Errors.Select(x => x.ErrorMessage)))</td>
        </tr>
        }
    }
</table>

<style>
    table.model-state
    {
        border-color: #600;
        border-width: 0 0 1px 1px;
        border-style: solid;
        border-collapse: collapse;
        font-size: .8em;
        font-family: arial;
    }

    table.model-state td
    {
        border-color: #600;
        border-width: 1px 1px 0 0;
        border-style: solid;
        margin: 0;
        padding: .25em .75em;
        background-color: #FFC;
    }
 </style>

Posted on Sun, 02 Feb 2020 09:47:32 -0500 by billf