Show ValidationSummary MVC3 as “alert-error” Bootstrap

后端 未结 16 884
情书的邮戳
情书的邮戳 2021-01-30 00:51

I want to show a ValidationSummary mcv3 with \"alert-error\" Bootstrap styling.

I\'m using a Razor view, and I show model errors with this code:

 @Html.V         


        
相关标签:
16条回答
  • 2021-01-30 01:40

    Alternative solution. =)

    @if (ViewData.ModelState.Any(x => x.Value.Errors.Any())) 
    { 
       // Bootstrap 2 = "alert-error", Bootstrap 3 and 4 = "alert-danger"
       <div class="alert alert-danger alert-error"> 
          <a class="close" data-dismiss="alert">&times;</a> 
          @Html.ValidationSummary(true, "Errors: ")
       </div>
    }
    
    0 讨论(0)
  • 2021-01-30 01:42

    edited again

    I misunderstood your question at first. I think the following is what you want:

    @if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Count > 0)
    { 
        <div class="alert alert-error">
            <button type="button" class="close" data-dismiss="alert">×</button>
            @Html.ValidationSummary(true, "Errors: ")
        </div>
    }
    
    0 讨论(0)
  • 2021-01-30 01:43

    I did not like how the ValidationSummary rendered using a bullet list (unordered list). It had a lot of unnecessary space below the error list.

    A solution to that issue - is simply to loop through the errors and render the errors how you want. I used paragraphs. For example:

    @if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
    {
        <div class="alert alert-danger" role="alert">
            <a class="close" data-dismiss="alert">×</a>
            @foreach (var modelError in Html.ViewData.ModelState.SelectMany(keyValuePair => keyValuePair.Value.Errors))
            {
                <p>@modelError.ErrorMessage</p>
            }
        </div>
    }
    

    The result, in my case, looks something like this:

    0 讨论(0)
  • 2021-01-30 01:43

    Consider writing an extension method to the HtmlHelper like:

    public static class HtmlHelperExtensions
    {
        public static HtmlString ValidationSummaryBootstrap(this HtmlHelper htmlHelper)
        {
            if (htmlHelper == null)
            {
                throw new ArgumentNullException("htmlHelper");
            }
    
            if (htmlHelper.ViewData.ModelState.IsValid)
            {
                return new HtmlString(string.Empty);
            }
    
            return new HtmlString(
                "<div class=\"alert alert-warning\">"
                + htmlHelper.ValidationSummary()
                + "</div>");
        }
    }
    

    Then you just need to fit the ul-li styling in your stylesheet.

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