如何在javascript中清除OnUnload事件中的asp.net会话值

时间:2013-07-21 11:59:31

标签: c# javascript html asp.net

我希望在浏览器关闭时清除ASP.NET会话值。我在我的html页面中定义了onunload函数,但我不知道如何在这个Javascript方法中清除会话值?

<body onunload="myUnloadFunction()">


<script>
function myUnloadFunction()
{
  // Needs asp.net session code here
}
</script>

请让我知道是否还有其他可取的做法。

1 个答案:

答案 0 :(得分:5)

试试这个:

代码隐藏:

[WebMethod]
public static void ClearYourSessionValue()
{
    // This will leave the key in the Session cache, but clear the value
    Session["YourKey"] = null;

    // This will remove both the key and value from the Session cache
    Session.Remove("YourKey");
}

JavaScript的:

$.ajax({
    type: "POST",
    url: "PageName.aspx/ClearYourSessionValue",
    data: "{}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
         // Do something interesting here.
    }
});

如果您想了解有关ASP.NET AJAX Page Methods的更多信息以及如何通过AJAX调用它们,请阅读Using jQuery to directly call ASP.NET AJAX page methods