0

I have a site and i want to set the user status in my database to 0 (Offline) when the user want to exit the site , the problem is i tried Page_Unload method but doesn't work and i found some Javascript code which works but this Javascript code shows a notification when you want to leave the site and in this code i want to call an ASP.NET method to change data in database but doesn't work.Thanks in advance!

    // Javascript code
  window.onbeforeunload = confirmExit;

function confirmExit() {  
    PageMethods.OnlineOut();
}

//This is on my Master Page
 <script type="text/javascript" src='<%= ResolveClientUrl("~/JavaScript.js") %>'></script>

 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

//This is on my Content Page.cs
 [WebMethod]
    public  void OnlineOut()
    {
        SqlConnection conexiune = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand SetareOnline = new SqlCommand("Update [dbo].[Table] Set Online=0 Where(UserName=@UserName)", conexiune);
                SetareOnline.Parameters.AddWithValue("@UserName", Session["Login"].ToString());
                conexiune.Open();
                SetareOnline.ExecuteNonQuery();
                conexiune.Close();
    }

1 Answers1

1

You stated that you tried Page_Unload and it didn't work; that you tried it implies that you haven't read up on the page lifecycle, documented clearly in MSDN. The function of the unload event is, from that link:

Unload is called after the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed.

For the functionality you wish to call, you'll need to investigate using AJAX from JavaScript, and handle the window.onbeforeunload event (see this StackOverflow question for a comprehensive answer).

That said, this still isn't guaranteed to work - it is still possible to quit a browser without triggering that call, and the user would be left as 'active'.

A much more reliable solution is to implement a "heartbeat" that runs at a scheduled interval (say, every ten seconds, or every minute) and calls a web service to say "Yes, I'm still here". You then record the last time the heartbeat was triggered, and count a user as offline if you haven't received a call within a set time (e.g. 2 minutes). See this question for ideas on this.

Community
  • 1
  • 1
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50