ModelState.IsValid == false, why?
Asked Answered
I

10

152

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.

Ihs answered 24/11, 2009 at 17:16 Comment(1)
This may be helpful of you want to get a list of errors: #5212748 There's a link to another larger post with more solution on that same problem.Ioyal
G
47

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

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.

Garth answered 24/11, 2009 at 19:6 Comment(4)
it seems to me that it should not, is it something wrong in Values.All(modelState => modelState.Errors.Count == 0) ?Ihs
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?Garth
ModelState.IsValid gives falseIhs
Ha-ha, that's obvious... how do you check for "values have 0 errors"?Garth
B
300

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

Biscuit answered 24/11, 2009 at 17:33 Comment(13)
could it be possible that all the values have 0 errors and the modelstate still be invalid ?Ihs
as said above, no this is not possible :). Somewhere must be an Error count!=0.Biscuit
As an add on, if the ErrorMessage is ambiguous to you, you can go to the keys and it'll show you which variable it's referring to.Madness
in your View, do: @Html.HiddenFor(model => model.Username) will solve the issue!Reinwald
very detailed Answer kudosBiennial
var asdf = ModelState.Values.Where(v => v.Errors.Count > 0); can help youBurg
The question states that there are zero errors. Your example is one where there are 1 errors. This answer should be removed.Vitalism
@SpencerSullivan The question states "Where can I find the list of errors of which make the ModelState invalid" appended with that the author could not find an error property. Not sure where you read 0 errors.Biscuit
The question stated "I didn't see any errors property on the ModelState object.". The answer shows an example where 1 error exists. The answer doesn't match the question's use case. Your answer, however, seems to be helping people per the up-votes, so rock on.Vitalism
I think you interpret it differently from most users. He couldn't find an error property, the errors were there or else it would have been valid. My answer shows where he could find the "error property", hidden away a bit deeper than most people expect. Not sure why at the time the .Errors property (which is there) was not shown in the debug popup but that is another story :).Biscuit
This is great when you only have 3 fields. What about when you have 20, 30, 50+ fields? Not really a very practical answer.Funke
For large numbers I would indeed probably write a quick query, although most likely first in my intermediate window at a debugger breakpoint or right into the quick watch window (SHIFT-F9 default). So, "it depends" applies once more :).Biscuit
In my case I has accidently added [Required] to a field that should not have had that attribute!Experiment
R
84

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();
Rollins answered 15/3, 2017 at 5:21 Comment(6)
Best answer here, should be rated higher. Why spend my time digging through 5 layers of the ModelState object in the debugger when I can just get the errors out of it. I'd be there all morning if I followed the highest rated answerZooplankton
this is the best everGudren
Or just paste ModelState.Where(x => x.Value.Errors.Count > 0).Select(x => new { x.Key, x.Value.Errors }) into your Watch window while debugging. No need to change code or recompile.Izettaizhevsk
This should be the answer. It addresses the OP's wish to see a list of errors. That's how I read it.Bestiality
This is accurate answerGastropod
Best answer! It saves to much time doing it this way. You can straight away pinpoint the problem.Primine
G
47

About "can it be that 0 errors and IsValid == false": here's MVC source code from https://github.com/Microsoft/referencesource/blob/master/System.Web/ModelBinding/ModelStateDictionary.cs#L37-L41

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.

Garth answered 24/11, 2009 at 19:6 Comment(4)
it seems to me that it should not, is it something wrong in Values.All(modelState => modelState.Errors.Count == 0) ?Ihs
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?Garth
ModelState.IsValid gives falseIhs
Ha-ha, that's obvious... how do you check for "values have 0 errors"?Garth
J
26
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))
    {

    }
Junker answered 24/11, 2009 at 17:30 Comment(2)
could it be possible that all the values have 0 errors and the modelstate still be invalid ?Ihs
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.Junker
D
17

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.

  }
Dinorahdinosaur answered 6/7, 2011 at 8:35 Comment(2)
This code was very helpful to me, but iterating the errors (Exceptions) to get each .Message resulted in "object reference not set to an instance of an object". When I changed z.Exception to z.ErrorMessage I was able to display the error messages.Softhearted
This was the solution for me, changing to z.ErrorMessage, although I didn't get an error with z.Exception, just null values. Probably worth updating the original answer.Antrim
Q
6

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.

Quadriceps answered 17/7, 2018 at 11:53 Comment(2)
Really helpful tip.Pellitory
This is the best advice in this thread. The problem I had was a stupid "." (dot) in UserNameSuzansuzann
B
4

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.

Beside answered 24/11, 2009 at 17:27 Comment(0)
J
3

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.

Juba answered 10/1, 2017 at 9:30 Comment(4)
This happened to me. Thx for the tip!Rankins
In my case it is not listing the error, but I don't understand what you mean by "without updating your form". Could you elaborate on exactly what needs to be updated?Maladapted
@Maladapted Yep - an example would be an edit form for a 'Person'. Say you added a new property onto the model - 'Surname' with a [Required] attribute - and then you don't add the corresponding input/Html.EditorFor to your formJuba
Yes. I added on Create Razor Page "Are You Sponsor" pulldown requiring a Yes or No answer. On my Edit Razor Page for same record I had not added this pulldown. It was required in my Model. thanks! So I went thru and pasted the above Immediate window query above all the Model.Isvalid statements and remmed it out so It is right there for future use!Naxos
E
1

Visual Studio 2022 + dotnet 6 update:

I had the same problem for a long time and finally I found it. In my case, it was the Id field :)

Just place a breakpoint and check your ModelState in runtime and go to this section :

ModelState -> Root -> Children

and you will see all valid and invalid Keys

enter image description here

Embank answered 24/9, 2022 at 20:32 Comment(0)
N
0

I pasted some JSON into MS Teams Wiki page for future reference, when I copied it back out for use, it added extra invisible characters. I confirmed this by linting it at JSONLint

Removing the extra characters fixed this error for me.

Ne answered 15/7, 2021 at 16:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.