The ModelState object in your controllers is crucial for validation. It tracks the validation state of your model after the model binder has attempted to populate it from the request. ModelState.IsValid: A boolean property that indicates whether all validation rules passed (true) or if there were any errors (false). ModelState.AddModelError: Manually add a model error for a specific property. Error Messages: Retrieve error messages associated with specific properties.
Code // Person.cs (Model) public class Person { // … other properties
[Required(ErrorMessage = “{0} can’t be blank”)] [Compare(“Password”, ErrorMessage = “{0} and {1} do not match”)] [Display(Name = “Re-enter Password”)] public string? ConfirmPassword { get; set; }
// … other properties }
// (In your controller action) public IActionResult Create(Person person) { if (!ModelState.IsValid) { return View(person); // Return to the view with validation errors }
// Model is valid, proceed with saving data } In this code: Data Annotations: The Person model uses data annotations to enforce validation rules. Model State Check: The controller action checks ModelState.IsValid. If false, the original view is re-rendered with the model object containing validation errors, allowing the user to correct them. Error Display: The view typically uses the @Html.ValidationSummary() and @Html.ValidationMessageFor() helper methods to display error messages to the user.