开发者

Detecting when user leaves page in Page_Load event

开发者 https://www.devze.com 2023-04-09 15:31 出处:网络
When a user leaves a page it fires of the Page_Load event again. How can I tell in code_behind that this is happening so in can avoid running the custom functions as the code in the Page_Load does not

When a user leaves a page it fires of the Page_Load event again. How can I tell in code_behind that this is happening so in can avoid running the custom functions as the code in the Page_Load does not really need to be 开发者_如何转开发ran when leaving the page?


When a user leaves a page it fires of the Page_Load event again

What do you mean by leaving a Page? Closing the browser or clicking Back button on browser? Or moving to another Page? Page_Load method is fired when on Loading Page or when Postback occurs on the same Page, but not leaving it.

Before you start any operations, you can (and you should) ensure that client is still connected and use HttpResponse.IsClientConnected property.

The IsClientConnected property returns false when the following conditions are true:

  1. The connection to the client was terminated. This can occur if the Close method was invoked, or if the client stopped execution of the Web page or browsed to another page.
  2. The HttpWorkerRequest object that is handling the request is null or the HttpWorkerRequest.IsClientConnected method returns false. If a custom HttpWorkerRequest object handles the request, then the HttpWorkerRequest.IsClientConnected method might be set based on custom criteria. For example, the custom worker request might force a time-out after a period of time.

http://msdn.microsoft.com/en-us/library/system.web.httpresponse.isclientconnected.aspx

EDIT

Switching tabs usually fires normal Postback, to detect it you should use:

private void Page_Load(object sender, System.EventArgs e)
{
    if (!Page.IsPostback)
    {
       //this is first load of this page
    }
}


If I understand the question correctly, you're looking for the IsPostBack property:

 private void Page_Load()
 {
    if (!IsPostBack)
    {
        // Any code here will only run the first time the page is loaded  
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号