views:

922

answers:

4

where can i see the list of errors of which make the modelstate invalid, i didn't saw any errors property on the modelstate object

+1  A: 

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.

tvanfosson
+3  A: 
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))
    {

    }
Michael G
could it be possible that all the values have 0 errors and the modelstate still be invalid ?
Omu
The modelstate will have a key "Property" and an associated error in the dictionary. the error message could be blank, but the error count will reflect the property count that are invalid. Because the ModelStateDictionary.AddModelError method takes a key, and Exception or error String; it's required to add a model error.
Michael G
+7  A: 

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.

alt text

bastijn
could it be possible that all the values have 0 errors and the modelstate still be invalid ?
Omu
as said above, no this is not possible :). Somewhere must be an Error count!=0.
bastijn
+2  A: 

About "can it be that 0 errors and IsValid == false": here's MVC source code from http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet#266501

public bool IsValid {
    get {
        return Values.All(modelState => modelState.Errors.Count == 0);
    }
}

Now, it looks like it can't be. Well, that's for ASP.NET MVC v1.

queen3
it seems to me that it should not, is it something wrong in Values.All(modelState => modelState.Errors.Count == 0) ?
Omu
Notice that error can be Message or Exception; for example Html.ValidationSummary does not display exceptions (for security reasons I guess); maybe that's why you don't see errors? How do you check for no errors?
queen3
ModelState.IsValid gives false
Omu
Ha-ha, that's obvious... how do you check for "values have 0 errors"?
queen3