Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ASP.NET MVC repopulate values in form when validation fails?

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.

like image 920
ckv Avatar asked Jan 13 '23 03:01

ckv


1 Answers

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.

like image 85
LukLed Avatar answered Jan 31 '23 00:01

LukLed