Saturday, January 10, 2015

Maintain JQuery Tab Active Position on PostBack C#

Recent, I decided to use the JQuery tabs in one of my projects.  I noticed really quickly that when I had a click event inside the tabs, it would return to the first tab.  Typically, you can use the AJAX UpdatePanel to handle partial PostBacks but in my case,  It wasn't updating correctly with other databound controls.  The snippet below will show you how to maintain your tabs on PostBack.


First, add your JQuery script tags in the head section.
<link href="../jquery-ui-1.11.1.custom/jquery-ui.min.css" rel="stylesheet"></link>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Next, add this script inside the header to initiate your tabs.
<script>
    $(function () {
        $("#tabs").tabs();
    });
</script>
Next, add this script function to the bottom of the page. This script will get the value from the hiddenfield control after PostBack.
 <script type="text/javascript">
        $(function () {
            $("#tabs").tabs({
                activate: function () {
                    var selectedTab = $('#tabs').tabs('option', 'active');
                    $("#<%= hdnSelectedTab.ClientID %>").val(selectedTab);
                },
                active: <%= hdnSelectedTab.Value %> + ""
            });
        });
    </script>
Next, add this hiddenfield control. This will be used to set the active tab when the PostBack occurs.
<asp:hiddenfield id="hdnSelectedTab" runat="server">
</asp:hiddenfield>
Finally, set the value of the hiddenfield control to the appropriate tab. To reset the value, set the value to 0 when the page is not a PostBack.
protected void btnCalShipping_Click(object sender, EventArgs e)
        {
            hdnSelectedTab.Value = "1";
        }

No comments:

Post a Comment