0

I have a page. There are some session variables those are used in a specified page only. How to clear those session variables when user left the page.

When user left the page using the menu/URL.

I have tried with

 protected void Page_Unload(object sender, EventArgs e)
    {
        Session["Rules"] = null;
        Session.Remove("Rules");
    }

But it is now working :(

Please suggest.

user1926138
  • 1,464
  • 7
  • 34
  • 53
  • if you want to use the storage for particular page then use `ViewState` but not `Session` : Session data is only useful for storing data beyond the lifetime of a page. If you don't want to store it beyond the life of a page then Session data is not for you here. – Krsna Kishore Feb 03 '16 at 08:55
  • @Webruster, I fear if ViewState can slow down the page – user1926138 Feb 03 '16 at 09:03
  • how much data you gonna store in `Session["Rules"]` ? – Krsna Kishore Feb 03 '16 at 09:07
  • What if the user closes his browser? You can't react on a clientside action at serverside. If the user clicks a hyperlink he will also be redirected immediately. The only workaround i can think of is using an invisible iframe(0 pixel size) and handle it's `onbeforeunload` event. There you could [use a `WebMethod`](http://stackoverflow.com/a/4760165/284240) to clear the session. But it's not worth the effort in my opinion. Either don't use the session for this purpose or let it expire. – Tim Schmelter Feb 03 '16 at 09:11

0 Answers0