How does ASP.NET MVC re-populate values ​​on a form when validation fails?

Web forms use presentation state. But in ASP.NET MVC, since model binding is available, properties can be easily obtained in the controller. However, when model validation fails, does ASP.NET MVC automatically populate form controls, realizing that the validation failed?

Or is there another way that this is done.

+4
source share
1 answer

There is a property called ModelState (in the Controller class) that contains all the values. It is used in model binding. When validation fails, ModelState contains all values ​​with validation errors.

ModelState.IsValid reports that the check did not cause errors.

ModelState.Values contains all values ​​and errors.

EDIT

Example for Ufuk:

View Model:

 public class EmployeeVM { public string FirstName { get; set; } public string LastName { get; set; } } 

Actions:

 [HttpGet] public ActionResult CreateEmployee() { return View(); } [HttpPost] public ActionResult CreateEmployee(EmployeeVM model) { model.FirstName = "AAAAAA"; model.LastName = "BBBBBB"; return View(model); } 

View:

 @model MvcApplication1.Models.EmployeeVM @using (Html.BeginForm("CreateEmployee", "Home")) { @Html.EditorFor(m => m) <input type="submit" value="Save"/> } 

As you can see, in the POST method, values ​​are overwritten with AAAAA and BBBBB, but after POST the form still displays the published values. They are taken from ModelState .

+9
source

Source: https://habr.com/ru/post/1486375/


All Articles