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 .