In this article I will explain how to maintain or retain the selected tab in jQuery UI Tabs on PostBack in ASP.Net
Cause
Before suggesting a solution it is a good idea to explain the case, this happens because jQuery UI Tabs plugin is not part of ViewState hence its Tab selection is lost.
Solution
Thus as a solution we will need to store the selected tab index in Hidden Field before PostBack and then fetch its value back on Page Load and set the Selected Tab using the index stored in the Hidden Field.
Maintain jQuery UI Tabs Selected Tab on PostBack
You will notice that I am making use of an ASP.Net HiddenField control which is set with the Index of the Current Selected Tab as soon as the Tab is selected using the select event handler of jQuery UI Tabs.
And then on the Selected Tab Index is fetched back from the Hidden Field and using this index the jQuery Tab is selected.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
var selected_tab = 1;
$(function () {
var tabs = $("#tabs").tabs({
select: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
});
</script>
<div id="tabs">
<ul>
<li><a href="#tabs-1">Tab 1</a></li>
<li><a href="#tabs-2">Tab 2</a></li>
<li><a href="#tabs-3">Tab 3</a></li>
</ul>
<div id="tabs-1">
Content 1
</div>
<div id="tabs-2">
Content 2
</div>
<div id="tabs-3">
Content 3
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
<asp:Button ID="Button1" runat="server" Text="Do PostBack" />
Now on server side I am fetching the value of the Hidden Field from the Request.Form collection and then setting it back into the Hidden Field. This is done because sometimes values set client side is not reflected directly in the Value property.
C#
protected void Page_Load(object sender, EventArgs e)
{
selected_tab.Value = Request.Form[selected_tab.UniqueID];
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
selected_tab.Value = Request.Form(selected_tab.UniqueID)
End Sub
Demo
Downloads