Remark :
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
[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); } |