Hide / Show menu code not working after postback

Posted by WraithNath on Stack Overflow See other posts from Stack Overflow or by WraithNath
Published on 2012-03-28T10:31:16Z Indexed on 2012/03/28 11:29 UTC
Read the original article Hit count: 172

Filed under:
|
|

I have a button on my web page that toggles the menu, After a postback the menu comes back despite me updating a hidden field value to store its state. Am I doing something wrong here? If there is a better way of doing it, let me know!

Markup:

    <asp:Button ID="btnMenu" runat="server" Text="Hide Menu" UseSubmitBehavior="False"
                                        OnClientClick="return toggleMenu(this);" />
    <asp:Panel runat="server" ID="pnlMenuToggle">
        //Main Menu
    </asp:Panel>
    <asp:Panel runat="server" ID="pnlSubMenuToggle">
        //Sub Menu
    </asp:Panel>
    <asp:HiddenField ID="hfMenuState" runat="server" Value="true" />

<script>


//Toggles menu visibility
        function toggleMenu(menuButton) {

            var menuVisible = $('#<%=hfMenuState.ClientID%>').val() == 'true' ? true : false;

            $('#<%=pnlMenuToggle.ClientID%>').slideToggleWidth();
            $('#<%=pnlSubMenuToggle.ClientID%>').slideToggle('slow');

            //Update whether the menu is visible
            menuVisible = !menuVisible;

            //Update menu button text
            $(menuButton).val(menuVisible ? 'Hide Menu' : 'Show Menu');

            $('#<%=hfMenuState.ClientID%>').val(menuVisible)

            return false;
        }
</script>

Code Behind:

(Page Load)

        bool menu = Convert.ToBoolean( hfMenuState.Value );

        pnlMenuToggle.Visible = menu;
        pnlSubMenuToggle.Visible = menu;

The javascripts updates the hidden field value but it looks like this is never posted back to the server.

What can I do to make sure the menu stays hidden after postbacks.

I have also tried putting the hidden field in an Update Panel with Update Mode set to Always

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about ASP.NET