ASP.NET MVC Validationsummary with excludePropertyErrors = true renders empty if the model is invalid
Asked Answered
S

4

10

Say you have a standard ValidationSummary:

<%: Html.ValidationSummary(excludePropertyErrors: true) %>

If the ModelState contains model errors for properties but not for the model itself the ValidationSummary renders the following HTML:

<div class="validation-summary-errors"><ul><li style="display:none"></li></ul></div>

Which is displayed as an empty list but is still visible because of the red border around the list. This seems to be a bug to me. Can I turn off that the ValidationSummary helper will ever render an empty list?

Siren answered 3/10, 2010 at 11:29 Comment(0)
U
11

Similar to usr's answer, I fixed this with the following:

public static IHtmlString FixedValidationSummary(this HtmlHelper htmlHelper)
{
    return htmlHelper.FixedValidationSummary(false);
}

public static IHtmlString FixedValidationSummary(this HtmlHelper htmlHelper,
    bool excludePropertyErrors)
{
    var result = htmlHelper.ValidationSummary(excludePropertyErrors);
    return result == null || result.ToString().Contains("display:none") ? null : result;
}

This way I don't have to actually fork the original.

Agreed, though, this is very annoying.

Unprofessional answered 28/4, 2011 at 19:52 Comment(0)
S
2

After I found out that there is no solution by looking at the source I solved the problem by forking the MVC version of the code and modifying one line.

Siren answered 8/10, 2010 at 15:9 Comment(1)
You only have to fork 3 functions.Siren
M
0

Another variation of the fix with Bootstrap classes is:

public static class ValidationSummaryExtensions
{
    public static MvcHtmlString CleanValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors, string message = null)
    {
        if(htmlHelper == null) throw new ArgumentNullException("htmlHelper");

        MvcHtmlString validationSummary = null;
        if (htmlHelper.ViewData.ModelState.ContainsKey(string.Empty))
        {
            var htmlAttributes = new { @class = "alert alert-danger" };
            validationSummary = htmlHelper.ValidationSummary(excludePropertyErrors, message, htmlAttributes);
        }

        return validationSummary;
    }
}
Mistake answered 4/3, 2014 at 12:10 Comment(0)
I
0

Another workaround is to move the style to the div. Here's the CSS:

div.validation-summary-valid {
    display: none;
}

When the summary returns with no errors the div is not displayed. When there are errors the class is automatically changed to validation-summary-errors.

Ingenuity answered 28/3, 2016 at 21:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.