Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can cause ViewData.ModelState.IsValid to become false

Tags:

There are times that I find my ModelState is invalid but can not find what has invalidated it since there are no ModelErrors. What is the easiest way to determine what has invalidated your model state if you yourself haven't added a ModelError?

like image 316
pondermatic Avatar asked Mar 26 '09 03:03

pondermatic


People also ask

What causes false IsValid ModelState?

IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

Which property is used to determine an error in ModelState?

In ASP.NET 5 MVC, the ModelState property of a controller represents the submitted values, and validation errors in those values if such errors exist, during a POST action. During the POST, the values submitted can be validated, and the validation process uses attributes defined by . NET like [Required] and [Range] .

What does ModelState 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.

How do I find my ModelState error?

You can use SelectMany function c# to get error message from modelstate mvc. It will generate error message string it contains modelstate errors; we can return as json and display in html element.


1 Answers

Looking at the asp.net mvc source code, the IsValid property on the ModelStateDictionary is simply returning true or false depending on whether there are any errors in the ModelState ICollection held in the Values property.

You should be able to find any errors including the message and exception like this:

foreach(var modelStateValue in ViewData.ModelState.Values) {     foreach(var error in modelStateValue.Errors)     {         // Do something useful with these properties         var errorMessage = error.ErrorMessage;         var exception = error.Exception;     } } 
like image 144
Steve Willcock Avatar answered Oct 24 '22 23:10

Steve Willcock