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