In this article I will explain with an example, how to solve the problem of Bootstrap Modal Popup Auto Closes on PostBack in ASP.Net using C# and VB.Net.
Bootstrap Modal Popup is opened from Client Side and hence when PostBack happens and Page refreshes, the Bootstrap Modal Popup disappears.
Hence in order to keep the Bootstrap Modal Popup across PostBacks, it has to be re-opened after PostBack from Server Side (Code Behind) using RegisterStartupScript method of ClientScript class.
HTML Markup
The following HTML Markup consists of an HTML Button element which will open the Bootstrap Modal Popup.
There’s an HTML DIV which will be displayed as Modal Popup Window using Bootstrap and it consists of a DropDownList assigned with a SelectedIndexChanged event handler.
<!-- Bootstrap -->
<script type="text/javascript" src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js'></script>
<script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" href='https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css'
media="screen" />
<!-- Bootstrap -->
<center>
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#MyPopup">
Open Modal</button>
</center>
<!-- Modal Popup -->
<div id="MyPopup" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
×</button>
<h4 class="modal-title">
Select Fruit
</h4>
</div>
<div class="modal-body">
<asp:DropDownList ID="ddlFruits" runat="server" AutoPostBack="true" OnSelectedIndexChanged="OnSelectedIndexChanged">
<asp:ListItem Text="Select Fruit" Value="0" />
<asp:ListItem Text="Mango" Value="1" />
<asp:ListItem Text="Apple" Value="2" />
<asp:ListItem Text="Banana" Value="3" />
</asp:DropDownList>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">
Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Popup -->
Keeping Bootstrap Modal Popup open across PostBacks in ASP.Net
Inside the SelectedIndexChanged event handler, the Bootstrap Modal Popup is re-opened by calling the modal function with parameter value show using RegisterStartupScript method of ClientScript class.
C#
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "Popup", "$('#MyPopup').modal('show')", true);
}
VB.Net
Protected Sub OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
ClientScript.RegisterStartupScript(Me.GetType(), "Popup", "$('#MyPopup').modal('show')", True)
End Sub
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads