Html 如何在 ASP.NET MVC 中获取模型状态错误的集合?

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

How do I get the collection of Model State Errors in ASP.NET MVC?

htmlasp.net-mvcvalidationspark-view-engine

提问by Ryan Montgomery

How do I get the collection of errors in a view?

如何获取视图中的错误集合?

I don't want to use the Html Helper Validation Summary or Validation Message. Instead I want to check for errors and if any display them in specific format. Also on the input controls I want to check for a specific property error and add a class to the input.

我不想使用 Html Helper 验证摘要或验证消息。相反,我想检查错误以及是否以特定格式显示它们。同样在输入控件上,我想检查特定的属性错误并向输入添加一个类。

P.S. I'm using the Spark View Engine but the idea should be the same.

PS 我使用的是 Spark View Engine,但想法应该是一样的。

So I figured I could do something like...

所以我想我可以做一些像......

<if condition="${ModelState.Errors.Count > 0}">
  DispalyErrorSummary()
</if>

....and also...

<input type="text" value="${Model.Name}" 
       class="?{ModelState.Errors["Name"] != string.empty} error" />

....

Or something like that.

或类似的东西。

UPDATE

更新

My final solution looked like this:

我的最终解决方案如下所示:

<input type="text" value="${ViewData.Model.Name}" 
       class="text error?{!ViewData.ModelState.IsValid && 
                           ViewData.ModelState["Name"].Errors.Count() > 0}" 
       id="Name" name="Name" />

This only adds the error css class if this property has an error.

如果此属性有错误,这只会添加错误 css 类。

回答by Chad Moran

<% ViewData.ModelState.IsValid %>

or

或者

<% ViewData.ModelState.Values.Any(x => x.Errors.Count >= 1) %>

and for a specific property...

并且对于特定的属性...

<% ViewData.ModelState["Property"].Errors %> // Note this returns a collection

回答by Chris McKenzie

To just get the errors from the ModelState, use this Linq:

要从 ModelState 中获取错误,请使用以下 Linq:

var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);

回答by Todd Menier

Condensed version of @ChrisMcKenzie's answer:

@ChrisMcKenzie 答案的精简版:

var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);

回答by UshaP

This will give you one string with all the errors with comma separating

这将为您提供一个字符串,其中包含逗号分隔的所有错误

string validationErrors = string.Join(",",
                    ModelState.Values.Where(E => E.Errors.Count > 0)
                    .SelectMany(E => E.Errors)
                    .Select(E => E.ErrorMessage)
                    .ToArray());

回答by Casey Crookston

Putting together several answers from above, this is what I ended up using:

将上面的几个答案放在一起,这就是我最终使用的:

var validationErrors = ModelState.Values.Where(E => E.Errors.Count > 0)
    .SelectMany(E => E.Errors)
    .Select(E => E.ErrorMessage)
    .ToList();

validationErrorsends up being a List<string>that contains each error message. From there, it's easy to do what you want with that list.

validationErrors最终成为List<string>包含每个错误消息的 。从那里,您可以轻松地使用该列表执行您想要的操作。

enter image description here

在此处输入图片说明

回答by Rake36

Thanks Chad! To show all the errors associated with the key, here's what I came up with. For some reason the base Html.ValidationMessage helper only shows the first error associated with the key.

谢谢乍得!为了显示与密钥相关的所有错误,这是我想出的。出于某种原因,基本的 Html.ValidationMessage 助手只显示与键相关的第一个错误。

    <%= Html.ShowAllErrors(mykey) %>

HtmlHelper:

HtmlHelper:

    public static String ShowAllErrors(this HtmlHelper helper, String key) {
        StringBuilder sb = new StringBuilder();
        if (helper.ViewData.ModelState[key] != null) {
            foreach (var e in helper.ViewData.ModelState[key].Errors) {
                TagBuilder div = new TagBuilder("div");
                div.MergeAttribute("class", "field-validation-error");
                div.SetInnerText(e.ErrorMessage);
                sb.Append(div.ToString());
            }
        }
        return sb.ToString();
    }

回答by MaylorTaylor

Here is the VB.

这里是VB。

Dim validationErrors As String = String.Join(",", ModelState.Values.Where(Function(E) E.Errors.Count > 0).SelectMany(Function(E) E.Errors).[Select](Function(E) E.ErrorMessage).ToArray())

回答by Gerard

If you don't know what property caused the error, you can, using reflection, loop over all properties:

如果您不知道是什么属性导致了错误,您可以使用反射循环遍历所有属性:

public static String ShowAllErrors<T>(this HtmlHelper helper) {
    StringBuilder sb = new StringBuilder();
    Type myType = typeof(T);
    PropertyInfo[] propInfo = myType.GetProperties();

    foreach (PropertyInfo prop in propInfo) {
        foreach (var e in helper.ViewData.ModelState[prop.Name].Errors) {
            TagBuilder div = new TagBuilder("div");
            div.MergeAttribute("class", "field-validation-error");
            div.SetInnerText(e.ErrorMessage);
            sb.Append(div.ToString());
        }
    }
    return sb.ToString();
}

Where T is the type of your "ViewModel".

其中 T 是“ViewModel”的类型。