Coder Perfect

In ASP.NET MVC, how can I acquire a collection of Model State Errors?

Problem

How can I retrieve a view’s collection of errors?

I don’t want to use the Validation Summary or Validation Message from the Html Helper. Instead, I’d like to look for problems and, if any are found, present them in a certain way. I also want to add a class to the input controls and check for a specific property error.

P.S. Although I’m using the Spark View Engine, the concept is the same.

So I figured I could do something like…

<if condition="${ModelState.Errors.Count > 0}">
  DisplayErrorSummary()
</if>

....and also...

<input type="text" value="${Model.Name}" 
       class="?{ModelState.Errors["Name"] != string.empty} error" />

....

Or something along those lines.

UPDATE

My ultimate solution was as follows:

<input type="text" value="${ViewData.Model.Name}" 
       class="text error?{!ViewData.ModelState.IsValid && 
                           ViewData.ModelState["Name"].Errors.Count() > 0}" 
       id="Name" name="Name" />

If this property has an error, this merely adds the error css class.

Asked by rmontgomery429

Solution #1

<% ViewData.ModelState.IsValid %>

or

<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

and in the case of a certain property…

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection

Answered by Chad Moran

Solution #2

Use this Linq to get only the errors from the ModelState:

var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

Answered by Chris McKenzie

Solution #3

The following is a condensed version of @ChrisMcKenzie’s response:

var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);

Answered by Todd Menier

Solution #4

This will give you one string with all the errors with comma separating

string validationErrors = string.Join(",",
                    ModelState.Values.Where(E => E.Errors.Count > 0)
                    .SelectMany(E => E.Errors)
                    .Select(E => E.ErrorMessage)
                    .ToArray());

Answered by UshaP

Solution #5

This is what I came up with after combining several of the replies above:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrors ends up being a List that contains each error message. From there, it’s easy to do what you want with that list.

Answered by Casey Crookston

Post is based on https://stackoverflow.com/questions/573302/how-do-i-get-the-collection-of-model-state-errors-in-asp-net-mvc