我有一个注册表单,其视图如下所示:
<div class="form-group">
@Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.Password, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.Password, "Please enter password.", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.ConfirmPassword, "Please confirm password.", new { @class = "text-danger" })
</div>
</div>
,动作结果如下:
[AllowAnonymous]
[HttpGet]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
//some code here
}
// If we got this far, something failed, redisplay form
return View(model);
}
甚至在我单击表单的提交按钮之前,就会触发验证错误消息。 我应该添加任何特定的代码来控制它吗?
答案 0 :(得分:1)
这是因为一件简单的事情而发生的事情:
显示视图的控制器操作将模型作为参数。 为什么会这样?
发生这种情况的原因是因为您的行为正在采取模型=&gt;在尝试填充视图模型时,默认模型绑定器正在踢,当它尝试为Password属性设置值时,如果请求中没有相应的值,它将自动向模型状态添加验证错误,因为您的模型属性是必需属性。
例如:
[HttpPost]
public ActionResult Process(MyViewModel model)
{
... if this action is called with a POST request and you have missed
to pass a value for the "Password" form parameter
you will get a validation error in the corresponding partial view
return View(model);
}