148

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.

ArunPratap
  • 4,816
  • 7
  • 25
  • 43
Omu
  • 69,856
  • 92
  • 277
  • 407
  • This may be helpful of you want to get a list of errors: https://stackoverflow.com/questions/5212248/get-error-message-if-modelstate-isvalid-fails There's a link to another larger post with more solution on that same problem. – carloswm85 Mar 03 '22 at 14:13

10 Answers10

296

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

bastijn
  • 5,841
  • 5
  • 27
  • 43
  • 4
    could it be possible that all the values have 0 errors and the modelstate still be invalid ? – Omu Nov 24 '09 at 18:21
  • 1
    as said above, no this is not possible :). Somewhere must be an Error count!=0. – bastijn Nov 24 '09 at 22:12
  • 2
    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. – Luminous Apr 30 '15 at 18:30
  • 2
    in your View, do: @Html.HiddenFor(model => model.Username) will solve the issue! – Umit Kaya Sep 04 '15 at 11:55
  • very detailed Answer kudos – Frank Odoom Feb 13 '18 at 11:44
  • 2
    `var asdf = ModelState.Values.Where(v => v.Errors.Count > 0);` can help you – Cirelli94 Jun 12 '18 at 07:48
  • The question states that there are zero errors. Your example is one where there are 1 errors. This answer should be removed. – Spencer Sullivan Sep 26 '19 at 15:55
  • @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. – bastijn Oct 09 '19 at 12:12
  • 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. – Spencer Sullivan Oct 14 '19 at 22:50
  • 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 :). – bastijn Oct 18 '19 at 10:40
  • This is great when you only have 3 fields. What about when you have 20, 30, 50+ fields? Not really a very practical answer. – elliotwesoff Mar 26 '20 at 19:09
  • 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 :). – bastijn Apr 01 '20 at 20:03
  • In my case I has accidently added [Required] to a field that should not have had that attribute! – Dave Stuart Oct 06 '21 at 13:18
79

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();
Krishna
  • 7,290
  • 3
  • 25
  • 25
  • 8
    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 answer – Sean T Jun 07 '19 at 11:16
  • 4
    this is the best ever – toy Jan 25 '20 at 02:02
  • 4
    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. – MGOwen May 19 '21 at 02:41
  • This should be the answer. It addresses the OP's wish to see a list of errors. That's how I read it. – Valamas Jun 30 '21 at 13:26
  • This is accurate answer – Kheersagar patel Dec 14 '22 at 15:46
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.

Haroen Viaene
  • 1,329
  • 18
  • 33
queen3
  • 15,333
  • 8
  • 64
  • 119
  • it seems to me that it should not, is it something wrong in Values.All(modelState => modelState.Errors.Count == 0) ? – Omu Nov 24 '09 at 20:15
  • 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 Nov 24 '09 at 22:15
  • 1
    ModelState.IsValid gives false – Omu Nov 25 '09 at 07:10
  • Ha-ha, that's obvious... how do you check for "values have 0 errors"? – queen3 Nov 25 '09 at 08:36
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))
    {

    }
Michael G
  • 6,695
  • 2
  • 41
  • 59
  • could it be possible that all the values have 0 errors and the modelstate still be invalid ? – Omu Nov 24 '09 at 18:23
  • 1
    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 Nov 24 '09 at 19:16
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.

  }
Jonas Stensved
  • 14,378
  • 5
  • 51
  • 80
  • 1
    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. – StackOverflowUser Jun 05 '17 at 10:38
  • 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. – esp Jul 12 '18 at 10:29
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.

Tom McDonough
  • 1,176
  • 15
  • 18
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.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
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.

AndyP9
  • 596
  • 4
  • 6
  • 1
    This happened to me. Thx for the tip! – Lewis86 Aug 01 '18 at 09:21
  • 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? – NickyLarson Feb 03 '22 at 13:52
  • 1
    @NickyLarson 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 form – AndyP9 Feb 04 '22 at 14:58
  • 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! – JustJohn Mar 10 '23 at 02:11
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

Mohammad Taheri
  • 348
  • 2
  • 9
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.

cdsln
  • 830
  • 1
  • 11
  • 33