如何在ASP中获取模型状态错误的集合。净MVC吗?

时间:2021-10-08 07:32:04

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助手验证摘要或验证消息。相反,我想检查是否有错误,以及是否有以特定格式显示的错误。同样在输入控件上,我想检查一个特定的属性错误并向输入添加一个类。

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

附注:我用的是Spark View引擎,但是想法应该是一样的。

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类。

8 个解决方案

#1


202  

<% 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

#2


59  

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

要从ModelState获得错误,请使用这个Linq:

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

#3


28  

Condensed version of @ChrisMcKenzie's answer:

浓缩版的@ChrisMcKenzie:

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

#4


22  

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());

#5


5  

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 helper只显示与密钥关联的第一个错误。

    <%= 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();
    }

#6


2  

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())

#7


1  

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();

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

validationErrors结尾是一个列表 ,其中包含每个错误消息。从那以后,你就可以很容易地按你的要求去做了。

如何在ASP中获取模型状态错误的集合。净MVC吗?

#8


0  

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”的类型。

#1


202  

<% 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

#2


59  

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

要从ModelState获得错误,请使用这个Linq:

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

#3


28  

Condensed version of @ChrisMcKenzie's answer:

浓缩版的@ChrisMcKenzie:

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

#4


22  

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());

#5


5  

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 helper只显示与密钥关联的第一个错误。

    <%= 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();
    }

#6


2  

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())

#7


1  

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();

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

validationErrors结尾是一个列表 ,其中包含每个错误消息。从那以后,你就可以很容易地按你的要求去做了。

如何在ASP中获取模型状态错误的集合。净MVC吗?

#8


0  

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”的类型。