Click here to Skip to main content
14,843,944 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi,

In my application I am using master page.

When I close any one of the chile pages in I want to delete all session and cache.
I can do that only on the page I am closing.

For Ex. I have a site.master page. And I have child page called test.aspx

I have written the below method on text.aspx.cs page, and I am calling this method on 'onunload' event
c#
[WebMethod]
public static void BrowserCloseMethod()
{
    //Removing all cache on closing of browser
    foreach (DictionaryEntry dEntry in HttpContext.Current.Cache)
          HttpContext.Current.Cache.Remove(dEntry.Key.ToString());
    HttpContext.Current.Session.Abandon();
    HttpRuntime.Close();
}

This code is working fine when I close test.aspx page.

But I can not keep on writing these methods in all child pages.
I added this method and tried to call this method on site.master.cs page.
But the method is not triggered.

Please help me achieve this. Thanks in advance
Posted

It should not work as expected because "onunload" event will fire on every postback.

However, if your code is working as expected, then the best way to apply all child pages...
1. Create a BasePage which will be inherited from System.Web.UI.Page.
2. Write your common methods in BasePage.
3. Create other child pages by inheriting BasePage.
   
Comments
srmohanr 27-May-14 7:14am
   
Thanks for your response.
I am facing another problem here.
Whenever I navigate from one page to another page, this method is calling and session gets Abandoned.
Please help
You can not add WebMethod to master page (master page can not be exists without a content page), so the only option you got is create a web-service (asmx) and add a static WebMethod decorated method to it.
This method can be called from JQuery as MyWebService.asmx/MyWebMethod. The javascript to do so can be common and linked to the master...

WebServer (Static.asmx)
C#
[ScriptService]
public class Static : WebService
{
    [WebMethod]
    [ScriptMethod( UseHttpGet = false, ResponseFormat = ResponseFormat.Json )]
    public string HelloWorld ( )
    {
        JavaScriptSerializer oJavaScriptSerializer = new JavaScriptSerializer( );

        return ( oJavaScriptSerializer.Serialize( "Hello World" ) );
    }
}


Master Page (Site.Master)
HTML
<html>
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-2.1.1.js"></script>
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            </asp:ContentPlaceHolder>
        </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: "Static.asmx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);
                }
            });
        });
    </script>
</body>
</html>
   
v2
Comments
srmohanr 27-May-14 7:30am
   
Can you pls give me an example for this.
Kornfeld Eliyahu Peter 27-May-14 9:02am
   
See updated solution...
The current page get unloaded from the server when you redirect to other page. So that is expected, what you need to do is on the client side, track if the browser is getting closed. In html or JS

<body onunload="SomeJavaScriptCode"></body>


In JavaScript:

window.onunload=function(){SomeJavaScriptCode};


Then, call a server side function, using AJAX, that will end the session and clear the cache
   
I have found another way when we are using master page.
On closing the browser window/tab, call another window (say text.aspx). In the page load event close all sessions and coockies.

Write the below code in site.master page
c#
var validNavigation = false;

function wireUpEvents() {

  var confirm_leave = 0; 
  var leave_message = 'Are you sure want to leave?'
  function goodbye(e) {
    if (!validNavigation) {
      if (confirm_leave!==1) {
        if(!e) e = window.event;
        //e.cancelBubble is supported by IE - this will kill the bubbling process.
        e.cancelBubble = true;
        e.returnValue = leave_message;
         var mywindow = window.open("test.aspx", "", "width=200, height=100");
         mywindow.close();
        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
          e.stopPropagation();
          e.preventDefault();
        }
        //return works for Chrome and Safari
        return leave_message;
      }
    }
  }
  window.onbeforeunload=goodbye;

  // Attach the event keypress to exclude the F5 refresh
  $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
  });

  // Attach the event click for all links in the page
  $("a").bind("click", function() {
    validNavigation = true;
  });

  // Attach the event submit for all forms in the page
  $("form").bind("submit", function() {
    validNavigation = true;
  });

  // Attach the event when the dropdown option is changed
  $("select#dropdownId").bind("change", function() {
   validNavigation = true;
  });

  // Attach the event click for all inputs in the page
  $("input[type=submit]").bind("click", function() {
    validNavigation = true;
  });

}

// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
  wireUpEvents();
});

On page load event of test.aspx
c#
protected void Page_Load(object sender, EventArgs e)
{
 foreach (DictionaryEntry dEntry in HttpContext.Current.Cache)
        HttpContext.Current.Cache.Remove(dEntry.Key.ToString());

 HttpContext.Current.Session.Clear();
 HttpContext.Current.Session.Abandon();
 HttpContext.Current.Session.RemoveAll();
 HttpRuntime.Close();
}
   
hi all My application is also have master and child pages. I am trying to get the logout time when browser is closed, I have tried to get the time in master page but it will not get the time in browser close when i put the code under master page onbeforeunload event. so i have changed my code to put the getting time code in all chaild pages onbeforeunload event it works fine.
So,i have tried with this solution, its works fine with me..
first create any .aspx page and in page load write which code do you want to run at the time of browser close.

I have done for getting the logout time and update it into log table. Below is my sample code for logout.aspx page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Windows;
using System.Configuration;
using System.Web.Services;
public partial class logout : System.Web.UI.Page
{
   public  string strConstr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
   public  DateTime utcTime = DateTime.UtcNow;
   public  TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
   public  DateTime localTime;
   public  int loginId;
    protected void Page_Load(object sender, EventArgs e)
    {
        localTime = TimeZoneInfo.ConvertTimeFromUtc(utcTime, tzi);
        loginId = Convert.ToInt32(Session["LoginId"].ToString());
        try
        {
            DateTime dtnow = localTime;

            SqlConnection cn = new SqlConnection(strConstr);
            cn.Open();
            SqlCommand cmd = new SqlCommand("updateLogoutTime", cn);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("LoginId", Convert.ToInt32(Session["LoginId"])));
            cmd.Parameters.Add(new SqlParameter("outDate", dtnow.Date));
            cmd.Parameters.Add(new SqlParameter("outTime", dtnow.ToString("HH:mm:ss tt")));
            cmd.ExecuteNonQuery();

        }
        catch (Exception ex)
        {
            Show(ex.Message.ToString());
        }        
    }
    
    public void Show(string msg)
    {
        Page page = HttpContext.Current.Handler as Page;
        if (page != null)
        {
            ScriptManager.RegisterStartupScript(page, page.GetType(), "msg", "alert('" + msg + "');", true);
        }
    }
}



and need to call the logout.aspx page in all other aspx pages of onbeforeunload event
like:

$(document).ready(function () {
           window.onbeforeunload = function () { updateLogout(); };
       });

       function updateLogout() {
           $.ajax({
               url: "logout.aspx",
               contentType: "application/json; charset=utf-8",
               type: "POST",
               success: function (data) {
               },
               error: function (x, y, z) {
               }
           });
       }


and need to put scriptmanager in all child pages to work the above script.
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900