How do you add Bootstrap’s close button to ValidationSummary in ASP.NET Forms?

How do you add Bootstrap’s close button to ValidationSummary in ASP.NET Forms?

I’m trying to get asp:ValidationSummary to use Bootstrap’s alert styles and to include a close button. The styling works, but the close button isn’t added.
This is how my .aspx looks like:

I’ve tried to get jQuery to add the button, in $(document).ready, like this:
$(‘.alert-dismissable’).each(function ()

This works just fine if I use a regular div element, but not with asp:ValidationSummary. If I examine the markup on the client, the button isn’t rendered there.
I’ve also tried subclassing asp:ValidationSummary to insert the markup in
Render (HtmlTextWriter writer). But the result is the same as with the previous attempts.
I’ve also tried to enclose the ValidationSummary inside a div, like this:

Which seems to render fine in the browser, but closing with the button prevents the ValidationSummary from showing up again as its parent div is now invisible.

Related:  How to get twitter bootstrap modal to close (after initial launch)


Solution 1:

I think you are on the right track with this

<div id="validationSummary" class="alert alert-danger alert-dismissable">
   <button type="button" class="close" data-dismiss="alert">&times;</button>
      ID="ValidationSummary1" ShowSummary="true" runat="server"

Additionally you need to handle the button click that causes validation to reset the visibility and then also clear the html from the validation summary.

$( "#myform" ).submit(function( event ) {
  //clear the validation summary html
  $("#ValidationSummary1").empty(); //this should be the ClientID not the serverID of your validation control.
  //display the validation summary div
  //you might want to remove the 'hidden' class instead of toggling the divs visibility

Solution 2:

i think this is the easiest way:

      var container = $('form').find('[data-valmsg-summary="true"]');
                container.find('ul').find('li').append('<a class="close" onclick="clearConfirmation()">×</a>');

  function clearConfirmation() {
            var container = $('form').find('[data-valmsg-summary="true"]');
            var html = container.html();

this is a pseudo-code just to give you an idea. Change clearConfirmation to your own needs and it will be good 🙂


Related:  Bootstrap collapse - go to top of the open item?