How to clear Session when navigating away from one page

ぐ巨炮叔叔 提交于 2019-12-23 04:13:20

问题


I googled this about 1/2 a hour no hit's. Scenario is that, dynamic scripts are saved in string builder whose "string" representation is stored in session. It just happens that when user navigates away from one page to another the script[from session] gets registered using "RegisterStartupScript". The script is registered in PreRender event of the Page. So i would like to clear this script in session while the page navigates away btw rule out a option to create another session variable and clear previous one. It's a overhead :(


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6421470/how-to-clear-session-when-navigating-away-from-one-page

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