我在MVC中使用AddModelError来显示错误消息,但我的问题是当我在输入值之前转到页面时我也看到了错误消息。我希望在推送提交后以及电子邮件为空时看到该消息。 这是我的控制器方法:
[Route("forgotPassword")]
public async Task<ActionResult> ForgotPassword(ForgotPasswordRequest forgotPasswordRequest)
{
string message = string.Empty;
try
{
if (ModelState.IsValid)
{
.....
else
{
ModelState.AddModelError("", Constants.MessageStrings.NoUser);
}
}
}
else
{
ModelState.AddModelError("", Constants.MessageStrings.RequiredFields);
}
}
catch (Exception exception)
{
...
return PartialView(message);
}
这是我的观点:
<div>
<p>Please enter the Email Address associated with your account and we will email you a link to reset your password.</p>
@using (Html.BeginForm("forgotPassword", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<label>
Email Address
<input type="email" name="email" placeholder="jdoe@example.com">
</label>
<input type="submit" value="Submit">
@Html.ValidationSummary(true)
}
答案 0 :(得分:4)
您需要将控制器操作分解为不同的方法。第一个只会返回一个新的ForgotPasswordRequest
,而第二个会检查ModelState
并执行实际的密码请求工作。
首先(GET)
[Route("forgotPassword")]
public async Task<ActionResult> ForgotPassword()
{
// no validation, just returns a new ForgotPasswordRequest for the the view
}
秒(POST)
[Route("forgotPassword")]
[HttpPost]
public async Task<ActionResult> ForgotPassword(ForgotPasswordRequest forgotPasswordRequest)
{
// checks the ModelState and performs the any other actions
}