In web forms the view state is used. But in ASP.NET MVC since model binding is available the properties can be easily acccessed in the controller. However when the model validation fails, does the ASP.NET MVC automatically populate the form controls realising that the validation has failed?
Or is there any other way by which this is accomplished.
There is an property called ModelState
(in Controller
class), that holds all the values. It is used in model binding. When validation fails, ModelState
holds all the values with validation errors.
ModelState.IsValid
tells you, that validation didn't throw any errors.
ModelState.Values
holds all the 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 POST method values are overwritten with AAAAA and BBBBB, but after POST, form still displays posted values. They are taken from ModelState
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With