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

后端 未结 9 1267
孤城傲影
孤城傲影 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:24

    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".

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

    Condensed version of @ChrisMcKenzie's answer:

    var modelStateErrors = this.ModelState.Values.SelectMany(m => m.Errors);
    
    0 讨论(0)
  • 2020-11-27 10:30

    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.

    0 讨论(0)
提交回复
热议问题