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
@if (ViewContext.ViewData.ModelState.Where(x => x.Key == "").Any())
{
@Html.ValidationSummary(true, null, new { @class = "ui-state-error" })
}
This checks if there are any model wide errors and only renders the summary when there are some.
ValidationSummary accepts an optional message parameter. If you set this parameter, then the box doesn't look as silly.
@Html.ValidationSummary(true, "Sorry, that didn't work. Please check the details submitted and try again.")
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.
Check this question too.
You could hide the summary with CSS:
.validation-summary-valid { display:none; }
Also, you could put the validation summary before the Html.BeginForm()
.
I was having this empty validation summary issue. I just set excludePropertyErrors
to false - and it added the errors to the validation summary.
@Html.ValidationSummary(false)
I realise this isn't necessarily what is being asked here - although this does solve the empty validation summary issue - and is an option if you're having this problem.
It's the validation scripts doing this.
Change the following the web.config
<add key="ClientValidationEnabled" value="false" />
It should be false