我注意到如果提交表单时出现错误,它会显示验证错误消息,这很酷。但是,它不会保留我输入的值。实际上,它们已经消失了,更糟糕的是 datepicker 也不起作用。所以,我不能再使用选择器了。所以,我的问题是:
- 如何保留我在验证之前输入的值?
- 如果可能的话,在发生验证错误后有什么方法可以重用选择器控件?
我注意到如果提交表单时出现错误,它会显示验证错误消息,这很酷。但是,它不会保留我输入的值。实际上,它们已经消失了,更糟糕的是 datepicker 也不起作用。所以,我不能再使用选择器了。所以,我的问题是:
假设您将表单值数据绑定到视图模型,只需在验证失败时将视图模型传递回视图。让我们看一个例子:
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()
}
我们使用 HtmlHelper 方法BeginForm
和EditorForModel
. 我们也可以使用EditorFor(model => model.UserName)
and EditorFor(model => model.Password)
。或者我们可以手动编写 HTML。重要的是 HTML 字段名称与我们的视图模型类中的属性匹配:
<input type="text" name="UserName" />
ASP.NET Mvc 会自动将表单元素数据绑定到HttpPost
动作中的 LoginViewModel。只需将无效模型传递回视图即可填充字段。