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:
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:
public class ViewModel {
[Required]
public string UserName { get; set; }
[Required, DataType(DataTypes.Password)]
public string Password { get; set; }
}
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);
}
}
@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.
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