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

前端 未结 11 1105
傲寒
傲寒 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:17
    @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.

    0 讨论(0)
  • 2020-12-13 14:20

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-13 14:23

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

    0 讨论(0)
  • 2020-12-13 14:23

    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.

    0 讨论(0)
  • 2020-12-13 14:23

    It's the validation scripts doing this.

    Change the following the web.config

    <add key="ClientValidationEnabled" value="false" />
    

    It should be false

    0 讨论(0)
提交回复
热议问题