Sanghoon Sanghoon - 1 year ago 127
C# Question

How to preserve values when MVC validation got errors?

I noticed that if there is an error when submit the form, it shows validation error message, that's cool. However, it doesn't keep my entered values. Actually, they are disappeared and even worse thing is datepicker won't work either. So, I couldn't use picker any more.
So, my questions are:

  1. how to preserve the values that I've entered before validation?

  2. if possible, any way to reuse picker control after validation error happened?

Answer Source

Assuming that you're data binding your form values to a view model, just pass the view model back to the view when validation fails. Let's look at an example:

The View Model:

public class ViewModel {
    public string UserName { get; set; }

    [Required, DataType(DataTypes.Password)]
    public string Password { get; set; }

The Controller:

public class LoginController : Controller {
    public ActionResult Login() {
        return View();

    public ActionResult Login(LoginViewModel model) {
        if( ModelState.IsValid ) {
            if( Membership.ValidateUser(model.UserName, model.Password) ) {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return Redirect("~/");

        // If we got this far, something went wrong.
        // Pass the model back to the view.
        return View(model);

The View:



We write the form HTML using the HtmlHelper methods BeginForm and EditorForModel. We could use EditorFor(model => model.UserName) and EditorFor(model => model.Password) as well. Or we could just write the HTML out by hand. The important thing is that the HTML field names match the properties in our view model class:

<input type="text" name="UserName" />

ASP.NET Mvc will data bind the form elements to the LoginViewModel in the HttpPost action automatically. Just pass the invalid model back to the View to have the fields populate.