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

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

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

提交回复
热议问题