Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve values when asp.net 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?
like image 775
San Avatar asked Aug 01 '12 19:08

San


1 Answers

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 {
    [Required]
    public string UserName { get; set; }

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

The Controller:

public class LoginController : Controller {
    [HttpGet]
    public ActionResult Login() {
        return View();
    }

    [HttpPost]
    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:

@Html.ValidationSummary()

using(@Html.BeginForm())
{
    @Html.EditorForModel()
}

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.

like image 135
Jesse Hallam Avatar answered Oct 04 '22 12:10

Jesse Hallam