I am learning MVC, and in ASP.Net MVC 3, what is the ModelState class ? I have looked on Google and MSDN, but I can't seem to get a clear understanding of it's purpose. Can anyone help?
In short, the ModelState is a collection of name and value pairs that are submitted to the server during a POST. It also contains error messages about each name-value pair, if any are found. ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft.
Clear() is required to display back your model object. If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState. Clear() to clean the ModelState values.
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 .
What Does ModelState Validation Validate? Model binding and model validation occur before executing a controller action in our APIs. Moreover, the ModelState object has an IsValid property where we can check its state.
Take a look at http://www.gxclarke.org/2010/05/consumption-of-data-in-mvc2-views.html under the ViewData.ModelState
section.
The ModelState property is a dictionary object that tracks HTTP values submitted to the server. In addition to storing the name and value of each field, it also tracks associated validation errors. Although its name may suggest otherwise, ModelState isn’t Model-aware. It doesn’t understand what a "Product" is. It simply contains a collection of items with names such as "ProductName" and "UnitPrice". It is the responsibility of other objects—ModelBinders, ViewResult, and the strongly-typed View—to map and interpret ModelState values as Model properties
The ModelState
Class in MVC is a class which contains the collection that has the key and values of the data submitted to server in the Post method.When MVC comes across the post it takes all the parameters in the post request and puts them in the instance of a ModelStateDictionary
. Whenever the ModelState
is active in server,the properties of the model are validated according to the validation attributes that are associated with them. And if any of the property is invalid it will be added to the error list. And the property ModelState.IsValid
will be set to false
. You can use this later on your code to check if everything is correct.
Refer this link for further information.
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