Search code examples
javascriptasp.netviewstate

ASP.NET - preserve style of HTML element after postback


I had long break from ASP.NET development.

I have a div, that is toggled by javascript function, on another element's onclick function.

 <div id="InsDetail" style="display: none">

After postback, the div's state is reverted back to collapsed. What is the easiest way to preserve style of this div between postbacks? (Viewstate maybe?)


Solution

  • You can use a hidden field (control) and update the state (e.g 1 = visible 0 = hidden) when change the visibility of the div. Next restore the state in load page event.

    more o less

    aspx file:

      <input runat="server" type="hidden" class="stateDiv" id='stateDiv' />
    

    js file or in page:

    $(function(){
     var visibility = $(".stateDiv").val();
     if(visibility== 1)
       $("#InsDetail").show()
     else
       $("#InsDetail").hide();
    
     $(your_botton).click(function(){
     //toggle div
      if ($("#InsDetail").is(":visible"))
         $(".stateDiv").val(1);
      else
        $(".stateDiv").val(0);
    });
    
    });
    

    In this way you can control the state also server-side