Search code examples
javascriptasp.netsession-storage

How can I persist local Javascript data on a page with postbacks, but clear it when the user navigates away?


I have a control in a large ASP.NET application. The control uses AJAX to communicate with the server, and stores a very large amount of state locally. All of the pages consuming this control make excessive use of ASP.NET post backs.

I need to persist the control's state across post backs, but I need the state to be wiped out when the user navigates away from the page, either by browsing to another location or performing a post back that redirects. I cannot send this state to the server and echo it back.

Currently, I'm using sessionStorage, but it doesn't satisfy the requirement that the state be wiped out if the user navigates away from the page.

As a caveat, I have zero control over the consumers of the control.

How can I accomplish this? Is this even possible?


Solution

  • I don't generally recommend this, but the following may actually be the best option for you since you are working within strict confines of the standard WebForms paradigm.

    You can implement IScriptControl on your control and add AJAX functionality using Microsoft Ajax, or alternatively create an extender that extends your control with AJAX capabilities.

    You'll want to use this in conjunction with an UpdatePanel so the control can still post back as usual and the ViewState mechanism remains intact, but the postback becomes an asynchronous communication with the server. Any control data, ViewState or otherwise, is local to the control/page, meeting your requirement that the data is cleared when you navigate away.