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

后端 未结 9 1266
孤城傲影
孤城傲影 2020-11-27 09:48

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 an

相关标签:
9条回答
  • 2020-11-27 10:15

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

    var modelStateErrors = this.ModelState.Keys.SelectMany(key => this.ModelState[key].Errors);
    
    0 讨论(0)
  • 2020-11-27 10:15

    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());
    
    0 讨论(0)
  • 2020-11-27 10:18
    <% 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
    
    0 讨论(0)
  • 2020-11-27 10:19

    Here is the 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())
    
    0 讨论(0)
  • 2020-11-27 10:22

    Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:

        var errors =
        from item in ModelState
        where item.Value.Errors.Count > 0
        select item.Key;
        var keys = errors.ToArray();
    

    Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error

    0 讨论(0)
  • 2020-11-27 10:24

    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.ShowAllErrors(mykey) %>
    

    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();
        }
    
    0 讨论(0)
提交回复
热议问题