C# 获取所有 ModelState 错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17580944/
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
Get all ModelState Errors on view
提问by Irineu Licks Filho
At my Controller I add some ModelState Errors. So, when I render my View, I want to get all these Errors and change the color of the labels of the fields that contain a error.
在我的控制器中,我添加了一些 ModelState 错误。因此,当我呈现我的视图时,我想获取所有这些错误并更改包含错误的字段标签的颜色。
So, I think I need to get all the ModelState Errors, get the field names and then change the color. This is the a good way?
所以,我想我需要获取所有 ModelState 错误,获取字段名称,然后更改颜色。这是一个好方法吗?
How can I get the ModelState Errors in my view?
如何在我的视图中获取 ModelState 错误?
采纳答案by Oleksii Aza
You can access it through ViewData.ModelState.
If you need more control with errors on your view you can use
您可以通过ViewData.ModelState. 如果您需要更多控制视图中的错误,您可以使用
ViewData.ModelState.IsValidField("name_of_input")
ViewData.ModelState.IsValidField("name_of_input")
or get a list of inputs with errors like this:
或获取包含以下错误的输入列表:
var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList();
回答by Darin Dimitrov
At my Controller I add some ModelState Errors. So, when I render my View, I want to get all these Errors and change the color of the labels of the fields that contain a error.
在我的控制器中,我添加了一些 ModelState 错误。因此,当我呈现我的视图时,我想获取所有这些错误并更改包含错误的字段标签的颜色。
That's exactly what's gonna happen if you add the model error with the exact same key in the ModelState as the Html.ValidationMessageFor helper you used in your view.
如果您在 ModelState 中使用与您在视图中使用的 Html.ValidationMessageFor 助手完全相同的键添加模型错误,这正是会发生的事情。
So for example let's suppose that in your form you've got the following snippet:
例如,让我们假设在您的表单中您有以下代码段:
@Html.LabelFor(x => x.Bazinga)
@Html.EditorFor(x => x.Bazinga)
@Html.ValidationMessageFor(x => x.Bazinga)
and in your HttpPost controller action you could add the following error message in order to highlight the Bazinga field:
在您的 HttpPost 控制器操作中,您可以添加以下错误消息以突出显示 Bazinga 字段:
ModelState.AddModelError("Bazinga", "Please enter a valid value for the Bazinga field");
And if you wanted to add some generic error message which is not associated to some specific input field you could always use the @Html.ValidationSummary()helper at the top of your form to display it. And in your controller action:
如果您想添加一些与某些特定输入字段无关的通用错误消息,您可以始终使用@Html.ValidationSummary()表单顶部的帮助程序来显示它。在您的控制器操作中:
ModelState.AddModelError(string.Empty, "Some generic error occurred. Try again.");
回答by Adrita Sharma
To display all the errors, try:
要显示所有错误,请尝试:
<div asp-validation-summary="All" class="text-danger"></div>
or,
或者,
<div class="text-danger">
@Html.ValidationSummary(false)
</div>

