我正在尝试同时使用ModelState.AddErrrorModel
和Html.ValidationMessage("Account")
来显示错误消息。
然而,即使我可以调试模型错误正在我的POST上添加,我再也无法在视图上看到它。
代码在表单的POST上运行,我可以看到正在调用ModelState.AddModelError
(ex.Message也有值):
try {
// code that fails in this case
}
catch (Exception ex)
{
logger.Error(ex);
ModelState.AddModelError("Register",ex.Message);
}
return RedirectToAction("Account", accountViewModel);
我的观点如下:
<h3>Get your free account now</h3>
@using (Html.BeginForm("Register", "Home", FormMethod.Post, new { @class = "form" }))
{
// trying to test different methods to get my errors... NOTHING works :)
@Html.ValidationSummary()
@Html.ValidationMessage("Register")
@Html.BusinessErrorMessageBox()
<div class="form-group">
<label>Email address</label>
@Html.TextBoxFor(m => m.RegisterViewModel.Email, new { @class = "form-control", placeholder = "Email", @type = "email" })
@Html.ValidationMessageFor(m => m.RegisterViewModel.Email)
</div>
<div class="form-group">
<label>Password</label>
@Html.PasswordFor(m => m.RegisterViewModel.Password, new { @class = "form-control", placeholder = "Password" })
@Html.ValidationMessageFor(m => m.RegisterViewModel.Password)
</div>
<div class="form-group">
<label>Your country (the country where you live or where your organization is registered in)</label>
@Html.DropDownListFor(model => model.RegisterViewModel.SelectedCountry, Model.RegisterViewModel.Countries, new { @class = "form-control" })
</div>
<input type="submit" class="btn btn-primary btn-lg" value="Get your free account now" />
}
出于实际原因,我的视图称为Account,接受POST的方法称为“Register”。
但无论我做什么,ValidationMessage
或ValidationSummary
都没有显示任何错误。
知道我做错了吗?
修改:
仅供参考:视图中有两种形式,如果可能有一种形式。
编辑2 :
单击转到我服务器的按钮时,可以看到输出以下HTML。值ex.Message
,无处显示:
<div class="validation-summary-valid" data-valmsg-summary="true"><ul><li style="display:none"></li>
</ul></div><span class="field-validation-valid" data-valmsg-for="Business" data-valmsg-replace="true"></span><span class="field-validation-valid" data-valmsg-for="Register" data-valmsg-replace="true"></span>
答案 0 :(得分:1)
POST操作的结果始终是重定向:
return RedirectToAction("Account", accountViewModel);
这意味着您的错误消息将会丢失,因为重定向会告诉浏览器发送另一个针对Account
操作的GET请求,您将在其中呈现新的注册视图错误。
您想要的流程是:
Account
,然后发送GET请求你的POST方法看起来像这样:
try {
//your logic here
//Everything worked, return a redirect
return RedirectToAction("Account", accountViewModel);
}
catch (Exception ex)
{
logger.Error(ex);
ModelState.AddModelError("Register",ex.Message);
}
//If we get here, something went wrong. Return the view so errors are displayed
return View("Account", accountViewModel);
希望它有所帮助!
答案 1 :(得分:0)