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".
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With