窗口关闭时调用C#函数

时间:2017-09-02 19:34:05

标签: javascript c# jquery asp.net

我尝试在用户点击浏览器中的“X”时调用c#中的函数但没有触发关闭事件(我尝试过:window.onbeforeunload$(window).unload以及$(window).unbind但没有任何效果。 这是我的Java脚本:

  <script>
    window.onbeforeunload = function () {
        PageMethods.endTaskChange();
    };
    $(window).unload(function () {
        PageMethods.endTaskChange();
    });
    $(window).unbind(function () {
        PageMethods.endTaskChange();
    })
</script>

我的代码背后有:

 [ScriptMethod]
    [WebMethod]
    public void endTaskChange()
    {
        if (HttpContext.Current.Request.QueryString["ID"] != null && HttpContext.Current.Request.QueryString["ID"].ToString() != string.Empty)
        {
            long TaskID = Convert.ToInt64(HttpContext.Current.Request.QueryString["ID"]);
            List<BusinessLayer.Tasks> olstTasks = new List<BusinessLayer.Tasks>();
            olstTasks = new TasksRepository().GetByID(TaskID);
            if (olstTasks.Count > 0)
            {
                Authentication oAuthentication = new Authentication();
                if (olstTasks[0].StatusID == 1 || (olstTasks[0].StatusID == 2 && olstTasks[0].ClosedByUserID == oAuthentication.getUser()[0].ID))
                {

                    BusinessLayer.Tasks oTasks = new BusinessLayer.Tasks();
                    oTasks.ID = TaskID;
                    oTasks.ClosedByUserID = oAuthentication.getUser()[0].ID;
                    oTasks.StatusID = 1;
                    oTasks.CloseDate = DateTime.Now;
                    oTasks.CloseNotes = "";
                    new TasksRepository().Close(oTasks);
                }
            }
        }

    }

有什么帮助吗?!!

1 个答案:

答案 0 :(得分:0)

试试这个:

$(window).on('beforeunload', function(){
         PageMethods.endTaskChange();
});

或者这个:

$(window).on('unload', function(){
        PageMethods.endTaskChange();
});