Why is ValidationSummary(true) displaying an empty summary for property errors?

前端 未结 11 1111
傲寒
傲寒 2020-12-13 13:51

I am having a slight issue with the use of ValidationSummary(true) to display model level errors. If the ModelState does not contain model errors (i.e. M

11条回答
  •  [愿得一人]
    2020-12-13 14:22

    I know this topic is old, but the behavior still exists even in MVC 5. It's definitely not the behavior most of us expect. When we want a "non-property" ModelState error, we do this:

    ModelState.AddModelError(string.Empty, ex.Message);
    

    Since we only want to display the summary if the empty key exists, this HtmlHelper does the trick and is cleaner than the accepted answer IMO:

    public static MvcHtmlString CustomValidationSummary(this HtmlHelper htmlHelper,
        bool excludePropertyErrors, string message = null)
    {
        // Don't render summary if there are no empty keys when excluding property errors
        if (excludePropertyErrors && !htmlHelper.ViewData.ModelState.ContainsKey(string.Empty))
            return null;
    
        // Use default
        return htmlHelper.ValidationSummary(excludePropertyErrors, message);
    }
    

    When excluding property errors, it's likely that you don't need the summary DIV available for client-side validation, so not rendering it at all is fine. I hope this helps some of you.

提交回复
热议问题