我在MVC中使用ModelState.AddModelError来显示视图中的错误消息。我有这段代码:
[HttpPost]
[Route("resetpassword")]
public ActionResult ResetPassword(ResetPasswordView resetPasswordView)
{
if(resetPasswordView.Password == resetPasswordView.ConfirmPassword)
{
.....
}
else
{
ModelState.AddModelError("", "Should be same password");
return View("ResetPassword");
}
return View("ThankYouResetPassword");
}
这是显示用户输入电子邮件和密码的3个文本框的视图,当点击提交上面的方法将执行时,我需要在2个文本框不相同时显示消息。
@model Models.ResetPasswordView
<div class="page resetPassword">
@using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<h5>Reset Your Loan Center Password</h5>
<table>
<tr><td>Email Address</td><td><input type="email" name="Email" placeholder="jdoe@example.com" readonly value="@Model.Email" size="25"></td></tr>
<tr><td>Password</td><td><input type="Password" name="Password" placeholder="Create Password" size="25"></td></tr>
<tr><td>Confirm Password</td><td><input type="Password" name="ConfirmPassword" placeholder="Re-enter Password" size="25"></td></tr>
<tr><td colspan="2"><input type="submit" value="Reset Password"></td></tr>
<tr>
<td class="errMessage" colspan="2">
@Html.ValidationSummary(true)
</td>
</tr>
</table>
}
因此,当代码转到需要显示错误消息的其他部分并进入查看时,我会在此行中获得null异常:
@using (Html.BeginForm("resetpassword", "Home", FormMethod.Post))
这是我得到的错误:
System.NullReferenceException: Object reference not set to an instance of an object.