Guilherme Calegari
Guilherme Calegari

Reputation: 303

Dynamically show bootstrap's surrounding error div on ValidationSummary?

I have a ASP .NET MVC 4.5 that uses Razor View Engine. I also added Bootstrap to it.

My doubt is: How do I dynamically show or hide a div according to the @Html.ValidationSummary()? - preferably without JQuery.

In my specific case, there's a form which contains several inputs. Whenever a validation error occours (eg. empty field), I intend to show the associated error message in a single div.

<div class="alert alert-danger">
@Html.ValidationSummary();
</div>

Thanks in advance.

Upvotes: 8

Views: 9380

Answers (2)

shenku
shenku

Reputation: 12448

This is all built into MVC no reason for any sort of hacking.

Simply use:

@Html.ValidationSummary(false, "", new { @class = "alert alert-danger" })

Assitionally some CSS to hide it when there are no errors:

.validation-summary-valid.alert-danger {
    display: none;
}

Much easier, much cleaner.

Upvotes: 24

hutchonoid
hutchonoid

Reputation: 33306

I would use an html helper which you could call like this:

         @Html.BootStrapValidationSummary();

Here is the code:

public static MvcHtmlString BootStrapValidationSummary(this HtmlHelper htmlHelper)
{
     var sb = new StringBuilder();

     var anyErrors = ViewData.ModelState.Values.Where( v => v.Errors.Count != 0 ).Any();
     var divBeginTag = @"<div class=""alert alert-danger"">";
     var divEndTag = @"</div>";

     if (anyErrors) {
         sb.AppendLine(divBeginTag);
         sb.AppendLine(htmlHelper.ValidationSummary());         
         sb.AppendLine(divEndTag);
         return new MvcHtmlString(sb.ToString());
     } 
     else
     {
       return new MvcHtmlString(sb.ToString());
     }


}

This is a quicker way but feels like a hack (I personally hate using if statements in views):

 @{
    var anyErrors = ViewData.ModelState.Values.Where( v => v.Errors.Count != 0 ).Any();
 }

@if (anyErrors) {
 <div class="alert alert-danger">
  @Html.ValidationSummary();
</div>
}

Upvotes: 4

Related Questions