Show ValidationSummary MVC3 as "alert-error" Bootstrap

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.ValidationSummary(true, "Errors: ")

It generates HTML code like this:

<div class="validation-summary-errors">
   <span>Errors:</span>
   <ul>
      <li>Error 1</li>
      <li>Error 2</li>
      <li>Error 3</li>
   </ul>
</div>

I tried with this too:

@Html.ValidationSummary(true, "Errors:", new { @class = "alert alert-error" })   

and it works ok, but without the close button (X)

It generates HTML code like this:

<div class="validation-summary-errors alert alert-error">
   <span>Errors:</span>
   <ul>
      <li>Error 1</li>
      <li>Error 2</li>
      <li>Error 3</li>
   </ul>
</div>

but Bootstrap alert should have this button into the div:

<button type="button" class="close" data-dismiss="alert">×</button>

Can anyone help?


This Works! - Thanks Rick B

@if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Count() > 0) 
{ 
   <div class="alert alert-error"> 
      <a class="close" data-dismiss="alert">×</a> 
      <h5 class="alert-heading">Ingreso Incorrecto</h5> 
      @Html.ValidationSummary(true)
   </div>
} 

I also had to remove the class ".validation-summary-errors" from "site.css", because that style defines other font color and weight.


Solution 1:

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

Solution 2:

This answer is based on RickB's one

  • Updated for the latest bootstrap ==>> alert-error doesn't exist in favor of alert-danger.

  • Works for all Validation Errors not only Key String.Empty ("")

For anyone using Bootstrap 3 and trying to get nice looking alerts:

if (ViewData.ModelState.Keys.Any(k=> ViewData.ModelState[k].Errors.Any())) { 
    <div class="alert alert-danger">
        <button class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
        @Html.ValidationSummary(false, "Errors: ")
    </div>
}

The solution provided by RickB works only on manually added errors on (String.Empty key) but not on those generated by ModelState (normally this gets triggered first via javascript but it's always a good practice to have a fallback if (for example) the Html.ValidationMessageFor is missing or many other situations.

Solution 3:

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