ASP.Net JQuery SlideToggle Postback Panel

I have an asp.net panel with a style that hides it, and I'm using jQuery for the slide. Drag the panel using the hyperlink. It works great. However, if I add a button on the page that causes the postback, the panel will default to hidden. I understand why this happens, but what is the best way to keep panels visible when postback occurs?

<head runat="server"> <title></title> <script type='text/javascript' src="jquery-1.4.1.min.js"> </script> <style type="text/css"> .panel { display: none; } </style> <script type="text/javascript"> $(function() { $("#Link1").click(function(evt) { evt.preventDefault(); $('#panelText').slideToggle('slow'); }); }); </script> </head> <body> <form id="form1" runat="server"> <asp:HyperLink ID="Link1" runat="server" NavigateUrl="#">SlideToggle </asp:HyperLink><br /> <asp:Panel ID="panelText" runat="server" CssClass="panel"> Some text</asp:Panel> <asp:Button ID="button1" runat="server" Text="Postback" /> </form> </body> </html> 
+4
source share
2 answers

This is how I solved my problem ...

 <head runat="server"> <title></title> <script type='text/javascript' src="jquery-1.4.1.min.js"> </script> <style type="text/css"> .panel { display: none; } </style> <script type="text/javascript"> $(function() { $("#Link1").click(function(evt) { evt.preventDefault(); $('#panelText').slideToggle('slow'); if ($('#panelText').hasClass('panel')) { $('#PanelState').attr('value', 'true'); } else { $('#PanelState').attr('value', 'false'); } }); }); $(document).ready(function() { if ($('#PanelState').attr('value') == 'false') { $('#panelText').addClass('panel'); } }); </script> </head> <body> <form id="form1" runat="server"> <asp:HiddenField ID="PanelState" runat="server" Value="false" /> <asp:HyperLink ID="Link1" runat="server" NavigateUrl="#">SlideToggle </asp:HyperLink><br /> <asp:Panel ID="panelText" runat="server"> Some text</asp:Panel> <asp:Button ID="button1" runat="server" Text="Postback" /> </form> </body> </html> 
+6
source

Add a hidden field in the form:

  <asp:HiddenField id="hdnPanelState" runat="Server" value="false" /> 

and change the JS function:

 <script type="text/javascript"> $(function() { $("#Link1").click(function(evt) { evt.preventDefault(); $('#panelText').slideToggle('slow'); //YOU WILL ALSO NEED TO CALCULATE IF SHOWING PANEL OR HIDING $("#hdnPanelState").attr("value","true");//Store Value }); }); </script> 
+4
source

Source: https://habr.com/ru/post/1306953/


All Articles