Show ValidationSummary MVC3 as "alert-error" Bootstrap

Gonzalo picture Gonzalo · Dec 13, 2012 · Viewed 70.2k times · Source

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.

Answer

Rick B picture Rick B · Dec 13, 2012

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