asp.net-mvc Html.ValidationSummary(false, "message") 始终显示,即使在页面加载时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4166997/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:34:47  来源:igfitidea点击:

Html.ValidationSummary(false, "message") is always showing, even on page load

asp.net-mvcvalidationvalidationsummary

提问by MondayPaper

I am using client side validation and I would like the message below to show only when I have an error. I am trying to use this a general error in case any field is invalid.
Currently

我正在使用客户端验证,我希望以下消息仅在出现错误时显示。我试图在任何字段无效的情况下使用这个一般错误。
目前

"* denotes required field"

“* 表示必填项”

is always showing even before validation.

甚至在验证之前总是显示。

<%: Html.ValidationSummary(false, "* denotes required field.")%>

I am using model binding to perform validation on client side and MVC.

我正在使用模型绑定在客户端和 MVC 上执行验证。

回答by Ryan O'Neill

If you use a developer tool in your browser to inspect the validation summary text you'll see that it has the class validation-summary-validwhen it is clear but validation-summary-errorswhen there are form errors.

如果您在浏览器中使用开发人员工具检查验证摘要文本,您会看到它在清晰但存在表单错误时具有该类。validation-summary-validvalidation-summary-errors

Therefore, just create a css rule as follows;

因此,只需创建如下 css 规则即可;

.validation-summary-valid {
    display:none;
}

and all should be good.

一切都应该很好。

回答by Mark P

I think the issue is the fact the Html.ValidationSummary has to appear before the Html.BeginForm otherwise the message is always displayed.

我认为问题在于 Html.ValidationSummary 必须出现在 Html.BeginForm 之前,否则总是显示消息。

回答by Kristianne Nerona

Initially I was checking for a List property on page load so I thought of passing a new model. Then the validation summary just appeared. When I changed my code from

最初我在页面加载时检查 List 属性,所以我想传递一个新模型。然后验证摘要刚刚出现。当我改变我的代码时

return View(new myModel)

to

return View()

the validation summary did not appear on Get. I also added a null check on the model when checking the property so I can use the latter code.

验证摘要未出现在 Get 上。在检查属性时,我还在模型上添加了空检查,以便我可以使用后一种代码。