Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 659
Omu Avatar asked Nov 24 '09 17:11

Omu


People also ask

How do you set ModelState IsValid to true?

If you want to remove only the errors you could loop through all elements in the ModelState and for each element remove the errors that might be associated to it. Once you do that, ModelState. IsValid will become true .

What ModelState is IsValid validate?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .

Why is ModelState not valid MVC?

The error typically means that your Model doesn't meet the requirements to be validated. In your example, your FirstName , LastName , Email , Subject and Message properties are decorated with the [Required] attribute. This means that those values shouldn't be null and empty otherwise your condition if(ModelState.

How do I clear ModelState errors?

To clear the memory of the model state you need to use ModelState. Clear().


2 Answers

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

like image 78
bastijn Avatar answered Oct 26 '22 00:10

bastijn


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(); 
like image 37
Krishna Avatar answered Oct 25 '22 23:10

Krishna