How to clear Session when navigating away from one page

拜拜、爱过 提交于 2019-12-06 15:50:31

Why are you storing this in Session, do you need to maintain this script in between GET requests?

If only postbacks are relevant you could store it in viewstate as this is maintained only when doing a postback.

If you want this string to be available on GET requests too you might want to introduce a different variable which has an identifier identifying the page for which the script is generated. If the requested page doesn't match the control variable you will have to generate a new script.

How is the user navigating away from the page? Can't you use an ASP.NET button instead of a hyperlink, and then do a Redirect in code once you have cleared your session variable?

protected void btnDoSomething_Click(object sender, EventArgs e)
{
    Session["Value"] = String.Empty;
    Response.Redirect(strURL, false);
}

OR You could add a variable in the query string and check it in the Page_Load event of the target page:

Webform1.aspx?reset=true

Since I cant comment yet, use onUnload().

It fires on full postbacks too. Ajax postbacks dont fire!

What you need to do, is guaranty inside the onUload function that you only clear the session when you want. Like setting a variable isPostBack to true before the postbacks so onUnload sees the variable and doenst send a request to clear the session.

Christian Kuetbach

You may use the JavaScript onUnload() and call an AJAX service, that will clear the server side session.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!