asp.net-mvc ASP.NET MVC Html.ValidationSummary(true) 不显示模型错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2818219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ASP.NET MVC Html.ValidationSummary(true) does not display model errors
提问by msi
I have some problem with Html.ValidationSummary. I don't want to display property errors in ValidationSummary. And when I set Html.ValidationSummary(true) it does not display error messages from ModelState. When there is some Exception in controller action on string
我对 Html.ValidationSummary 有一些问题。我不想在 ValidationSummary 中显示属性错误。当我设置 Html.ValidationSummary(true) 时,它不会显示来自 ModelState 的错误消息。当字符串上的控制器操作出现异常时
MembersManager.RegisterMember(member);
catch section adds an error to the ModelState:
catch 部分给 ModelState 添加了一个错误:
ModelState.AddModelError("error", ex.Message);
But ValidationSummary does not display this error message. When I set Html.ValidationSummary(false) all messages are displaying, but I don't want to display property errors. How can I fix this problem?
但 ValidationSummary 不显示此错误消息。当我设置 Html.ValidationSummary(false) 时,所有消息都显示,但我不想显示属性错误。我该如何解决这个问题?
Here is the code I'm using:
这是我正在使用的代码:
Model:
模型:
public class Member
{
[Required(ErrorMessage = "*")]
[DisplayName("Login:")]
public string Login { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Password:")]
public string Password { get; set; }
[Required(ErrorMessage = "*")]
[DataType(DataType.Password)]
[DisplayName("Confirm Password:")]
public string ConfirmPassword { get; set; }
}
Controller:
控制器:
[HttpPost]
public ActionResult Register(Member member)
{
try
{
if (!ModelState.IsValid)
return View();
MembersManager.RegisterMember(member);
}
catch (Exception ex)
{
ModelState.AddModelError("error", ex.Message);
return View(member);
}
}
View:
看法:
<% using (Html.BeginForm("Register", "Members", FormMethod.Post,
new { enctype = "multipart/form-data" })) {%>
<p>
<%= Html.LabelFor(model => model.Login)%>
<%= Html.TextBoxFor(model => model.Login)%>
<%= Html.ValidationMessageFor(model => model.Login)%>
</p>
<p>
<%= Html.LabelFor(model => model.Password)%>
<%= Html.PasswordFor(model => model.Password)%>
<%= Html.ValidationMessageFor(model => model.Password)%>
</p>
<p>
<%= Html.LabelFor(model => model.ConfirmPassword)%>
<%= Html.PasswordFor(model => model.ConfirmPassword)%>
<%= Html.ValidationMessageFor(model => model.ConfirmPassword)%>
</p>
<div>
<input type="submit" value="Create" />
</div>
<%= Html.ValidationSummary(true)%>
<% } %>
回答by Jab
I believe the way the ValidationSummary flag works is it will only display ModelErrors for string.empty
as the key. Otherwise it is assumed it is a property error. The custom error you're adding has the key 'error' so it will not display in when you call ValidationSummary(true). You need to add your custom error message with an empty key like this:
我相信 ValidationSummary 标志的工作方式是它只会显示 ModelErrorsstring.empty
作为关键。否则,它被认为是一个属性错误。您添加的自定义错误具有键“错误”,因此当您调用 ValidationSummary(true) 时它不会显示。您需要使用空键添加自定义错误消息,如下所示:
ModelState.AddModelError(string.Empty, ex.Message);
回答by ingvesund
This works better, as you can show validationMessage for a specified key:
这效果更好,因为您可以为指定的键显示验证消息:
ModelState.AddModelError("keyName","Message");
and display it like this:
并像这样显示它:
@Html.ValidationMessage("keyName")
回答by Levitikon
I know this is kind of old and has been marked as answers with 147 up votes, but there is something else to consider.
我知道这有点陈旧,并且已被标记为获得 147 票支持的答案,但还有其他事情需要考虑。
You can have all the model errors, the property named and string.Empty keys alike, be shown in the ValidationSummary if you need to. There is an overload in the ValidationSummary that will do this.
如果需要,您可以在 ValidationSummary 中显示所有模型错误、named 属性和 string.Empty 键。ValidationSummary 中有一个重载可以做到这一点。
// excludePropertyErrors:
// true to have the summary display model-level errors only, or false to have
// the summary display all errors.
public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors);
回答by Piotr Knut
Maybe like that:
也许是这样的:
[HttpPost]
public ActionResult Register(Member member)
{
try
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("keyName", "Form is not valid");
return View();
}
MembersManager.RegisterMember(member);
}
catch (Exception ex)
{
ModelState.AddModelError("keyName", ex.Message);
return View(member);
}
}
And in display add:
并在显示中添加:
<div class="alert alert-danger">
@Html.ValidationMessage("keyName")
</div>
OR
或者
<div class="alert alert-danger">
@Html.ValidationSummary(false)
</div>
回答by sachind
@Html.ValidationSummary(false,"", new { @class = "text-danger" })
Using this line may be helpful
使用这条线可能会有所帮助
回答by Allan Patrick Patzlaff
In my case it was not working because of the return.
就我而言,由于返回,它不起作用。
Instead of using:
而不是使用:
return RedirectToAction("Rescue", "CarteiraEtapaInvestimento", new { id = investimento.Id, idCarteiraEtapaResgate = etapaDoResgate.Id });
I used:
我用了:
return View("ViewRescueCarteiraEtapaInvestimento", new CarteiraEtapaInvestimentoRescueViewModel { Investimento = investimento, ValorResgate = investimentoViewModel.ValorResgate });
It′s a Model, so it is obvius that ModelState.AddModelError("keyName","Message");
must work with a model.
这是一个模型,所以很明显ModelState.AddModelError("keyName","Message");
必须使用模型。
This answer show why. Adding validation with DataAnnotations
这个答案说明了原因。 使用 DataAnnotations 添加验证
回答by alex
If nearly everything seems right, another thing to look out for is to ensure that the validation summary is not being explicitly hidden via some CSSoverride like this:
如果几乎一切看起来都正确,另一件需要注意的事情是确保验证摘要没有通过像这样的CSS覆盖被显式隐藏:
.validation-summary-valid {
display: none;
}
This may also cause the @Html.ValidationSummary
to appear hidden, as the summary is dynamically rendered with the validation-summary-valid
class.
这也可能导致@Html.ValidationSummary
显示为隐藏,因为摘要是使用validation-summary-valid
类动态呈现的。
回答by Adrita Sharma
You can try,
你可以试试,
<div asp-validation-summary="All" class="text-danger"></div>
回答by ronIT
ADD it in the lowermost part og your View:
将它添加到您的视图的最下方:
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }
@section 脚本 { @Scripts.Render("~/bundles/jqueryval") }