[c#] ModelState.IsValid == false, why?

Where can I find the list of errors of which make the ModelState invalid? I didn't see any errors property on the ModelState object.

This question is related to c# asp.net-mvc modelstate

The answer is


bool hasErrors =  ViewData.ModelState.Values.Any(x => x.Errors.Count > 1);

or iterate with

    foreach (ModelState state in ViewData.ModelState.Values.Where(x => x.Errors.Count > 0))
    {

    }

If you remove the check for the ModelsState.IsValid and let it error, if you copy this line ((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors and paste it in the watch section in Visual Studio it will give you exactly what the error is. Saves a lot of time checking where the error is.


The ModelState property on the controller is actually a ModelStateDictionary object. You can iterate through the keys on the dictionary and use the IsValidField method to check if that particular field is valid.


Sometimes a binder throwns an exception with no error message. You can retrieve the exception with the following snippet to find out whats wrong:

(Often if the binder is trying to convert strings to complex types etc)

 if (!ModelState.IsValid)
            {
var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

// Breakpoint, Log or examine the list with Exceptions.

  }

As has just happened to me - this can also happen when you add a required property to your model without updating your form. In this case the ValidationSummary will not list the error message.


As you are probably programming in Visual studio you'd better take advantage of the possibility of using breakpoints for such easy debugging steps (getting an idea what the problem is as in your case). Just place them just in front / at the place where you check ModelState.isValid and hover over the ModelState. Now you can easily browse through all the values inside and see what error causes the isvalid return false.

modelstate


Paste the below code in the ActionResult of your controller and place the debugger at this point.

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();