Search code examples
c#asp.netweb-servicesasmxpagemethods

Calling a Page Method when the Browser Closes


Hi here I'm trying to call a [webmethod] on bodyunload method.

But it is getting fired on page load itself only. How do i prevent it?

Here's the code I am using:

[WebMethod]
public static void AbandonSession()
{
    HttpContext.Current.Session.Abandon();
}


<script language="javascript" type="text/javascript">
//<![CDATA[

function HandleClose() {
    PageMethods.AbandonSession();
}

//]]>
</script>

<body onunload="HandleClose()">
....
....
....
</body>

Thank you, Nagu


Solution

  • I have tested with below code and it is working fine.

    In Aspx page

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
    
        <script type="text/javascript">
            //<![CDATA[
    
            function HandleClose()
            {
    
    
                PageMethods.AbandonSession();
            }
    
            //]]>    
        </script>
    
    </head>
    <body onunload="HandleClose()">
        <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        </form>
    </body>
    </html>
    

    In Codebehind

    using System;
    using System.Collections.Generic;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    
    public partial class ClearSessionOnPageUnload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
    
        }
        [WebMethod]
        public static void AbandonSession()
        {
            HttpContext.Current.Session.Abandon();
        }
    
    }
    

    You can put breakpoint at AbandonSession method to verify that it is getting hit at unload.