Question

We are following a procedure in our work while developing a web page, is to bind page to one or more session variables, these session variables are used only for that page, to hold current processing objects, so while closing page no need for them.

How could I discard these session variables while closing page? Any suggestions regarding that technique or how to solve that problem?

Was it helpful?

Solution

There is no server-side event that is raised when a page is left/closed. Also the Session_End event (mentioned in other answers) is not called when a page is left, since the user might navigate to other pages of the same web application (and therefore the session will continue to exist).

I can think of 3 possible ways to solve (or work around) this issue:

1 - use ViewState to store data with page-scope. This is what ViewState is made for, and unless you have a lot of data, it should not be a problem. If you have a lot of data, remember, that it will be serialized/deserialized and sent to the client/back to the server for every request (which may result in large requests and therefore bad performance).

2 - instead of putting the data into the session, put it into the Cache (with a low sliding expiration timeout). On your page, you can access your data in the same way as from the session, i.e. data = Cache["data"], but you have to be prepared that the data was removed from the Cache (you have to re-load it again from DB for example), if the time between two requests was bigger than the expiration time.

3 - use the client-side (javascript) onUnload event, and trigger some action (e.g. a ajax callback) to remove the data from the session. But I think the onUnload event is not reliable (it will not be fired in any case, e.g. when the browser is terminated by a crash or with the task manager, or if javascript is disabled).

OTHER TIPS

If you use variables for only that page, store them in viewstate. ViewState is suitable for page scoped variables.

If you are using ASP.NET sessions (which you probably are), you can add a global.asax file to your soluting. In there this event-delegate is to be found (if not, create it):

protected void Session_End(object sender, EventArgs e)
{

}

.. In here you can clear your session collection.

    protected void Session_End(object sender, EventArgs e)
    {
        Session.Clear();
    }

This will be fired when the session expires or when a user clicks logout :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top