What does ModelState.IsValid do?

When I create a method, I bind my object to a parameter, and then check if the ModelState is ModelState , so I add to the database:

But when I need to change something before adding to the database (before I changed it, ModelState cannot be valid, so I have to do it) why the state of the model is still invalid.

What exactly does this function check?

This is my example:

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) { encaissement.Montant = Convert.ToDecimal(encaissement.Montant); ViewBag.montant = encaissement.Montant; if (ModelState.IsValid) { db.Encaissements.Add(encaissement); db.SaveChanges(); return RedirectToAction("Index", "Encaissement"); }; ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP"); return View(encaissement); } 
+22
c # asp.net-mvc
source share
3 answers

ModelState.IsValid indicates whether it was possible to correctly associate the incoming values ​​from the request with the model and whether any explicitly defined verification rules were violated during the model binding process.

In your example, the associated model is of the Encaissement class Encaissement . Validation rules are rules specified in the model using attributes, logic, and errors added in the IValidatableObject Validate() method or simply in the code of the action method.

The IsValid property will be true if the values ​​were able to correctly bind to the model AND no validation rules were violated in the process.

Here is an example of how the validation attribute and IValidatableObject can be implemented in your model class:

 public class Encaissement : IValidatableObject { // A required attribute, validates that this value was submitted [Required(ErrorMessage = "The Encaissment ID must be submitted")] public int EncaissementID { get; set; } public DateTime? DateEncaissement { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { var results = new List<ValidationResult>(); // Validate the DateEncaissment if (!this.DateEncaissement.HasValue) { results.Add(new ValidationResult("The DateEncaissement must be set", new string[] { "DateEncaissement" }); } return results; } } 

Here is an example of how the same validation rule can be applied in the action method of your example:

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "EncaissementID,libelle,DateEncaissement,Montant,ProjetID,Description")] Encaissement encaissement) { // Perform validation if (!encaissement.DateEncaissement.HasValue) { this.ModelState.AddModelError("DateEncaissement", "The DateEncaissement must be set"); } encaissement.Montant = Convert.ToDecimal(encaissement.Montant); ViewBag.montant = encaissement.Montant; if (ModelState.IsValid) { db.Encaissements.Add(encaissement); db.SaveChanges(); return RedirectToAction("Index", "Encaissement"); }; ViewBag.ProjetID = new SelectList(db.Projets, "ProjetId", "nomP"); return View(encaissement); } 

Keep in mind that the property value types of your model will also be checked. For example, you cannot assign a string value to the int property. If you do, it will not be bound, and an error will be added to your ModelState .

In your example, the EncaissementID value cannot have the value "Hello" sent to it, this will add a model validation error, and IsValid will be false.

For any of the above reasons (and possibly more), the bool IsValid value of the model state will be false .

+26
source share

ModelState.IsValid will basically tell you if there are any problems with your data sent to the server based on data annotations added to the properties of your model.

If, for example, you have [Required(ErrorMessage = "Please fill")] , and this property will be empty when you submit the form to the server, ModelState will be invalid.

ModelBinder also checks out some basic things for you. For example, if you have a date picker, and the property that this picker is bound to is not NULL, which can be NULL, your ModelState will also be invalid if you left the date empty.

Here and here are some useful posts to read.

+13
source share

You can find an excellent article on ModelState and its use here .

In particular, the IsValid property is a quick way to check if there are any field validation errors in ModelState.Errors . If you are not sure what caused your model to become invalid by the time it sent the POST method to your controller method, you can check the ModelState["Property"].Errors property, which should result in at least one validation error forms.

Change: updated with correct dictionary syntax from @ChrisPratt

+3
source share

All Articles