Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net webforms and jquery: How to save/restore jquery state between postbacks?

I am building a asp.net webforms (3.5 sp1) application, using jquery where I can to animate the UI, change its state. It has worked great until I started doing postbacks, where the UI obviously resets itself to its initial state.

So my question is, what are the best practices for saving and restoring jquery/UI state between postbacks?

Thanks, Egil.

Update: Thanks a lot guys, great input, to bad I cant mark more than one answer as the "answer".

like image 409
Egil Hansen Avatar asked Dec 10 '22 22:12

Egil Hansen


1 Answers

I typically store things like menu state or filter (set of inputs in a div) visibility, etc. server-side in the session via AJAX. When a menu expands or a filter is shown, the click handler will fire an AJAX event to a web service that will record the state of the menu or filter visibility in the user's session. On a postback I use the session variables corresponding to each menu/filter to set it's initial state via CSS. I find that this is better user experience since the page doesn't flash when it is updated by javascript after loading if you make the changes client-side.

Example -- as I'm on the road this not actual code from a project and may be incomplete. Uses jQuery. The Url for the web service is going to depend on how you implement web services. I'm using ASP.NET MVC (mostly) so mine would be a controller action.

<script type='text/javascript'>
    $(document).ready( function() {
       $('#searchFilter').click( function()  {
           var filter = $(this);
           var filterName = filter.attr('id');
           var nowVisible = filter.css('display') === 'none';
           if (nowVisible) {
              filter.show();
           }
           else {
              filter.hide();
           }
           $.post('/controller/SetFilterVisibility',
                  { name: filterName, visibility: nowVisible } );
       });
    });
</script>


<div id='searchFilter' <%= ViewData["searchFilterVisibility"] %> >
    ...
</div>

Server-side code

[AcceptVerbs( HttpVerbs.POST )]
[Authorization]
public ActionResult SetFilterVisibility( string name, bool visible )
{
    Session[name] = visible;
    return Content( string.Empty );  // not used... 
}

[AcceptVerbs( HttpVerbs.GET )]
[Authorization]
public ActionResult SomeAction( int id )
{
    ...
    ViewData["searchFilterVisibility"] = Session["searchFilter"];
    ...
    return View();
}
like image 109
tvanfosson Avatar answered Dec 13 '22 14:12

tvanfosson