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?
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.
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] .
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.
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With