从Javascript调用ASP.NET方法 [英] Call a ASP.NET method from Javascript

查看:81
本文介绍了从Javascript调用ASP.NET方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!我有一个网站,我想将我的数据库中的用户状态设置为0(离线),当用户想要退出网站,问题是我尝试了Page_Unload方法,但不起作用,我发现一些Javascript代码工作,但当你想要离开网站时,这个Javascript代码会显示一个通知,在这段代码中,我想调用一个ASP.NET方法来更改数据库中的数据,但是不起作用。提前谢谢!



Hi! 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();
    }

推荐答案

在你之前很多 - 你错过了onbeforeunload事件处理程序......

请在此处阅读: https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onbeforeunload [ ^ ]

从中您可以理解,事件处理程序用于设置离开页面时显示给用户的消息...

此时它甚至不确定他是否会离开他可以选择取消所有页面!

所以 - 如果你的代码工作正常,你会感到抱歉...

在CP上做一篇小文章搜索,你会找到一些帮助......
As a lot before you - you missed the onbeforeunload event handler...
Read here: https://developer.mozilla.org/en-US/docs/WindowEventHandlers.onbeforeunload[^]
From that you can understand that the event handler is used to set the message displayed to user upon leaving the page...
At this point it not even sure he will leave the page at all as he can choose cancel too!
So - if your code WAS working you would be sorry for that...
Do a little article search in CP, you will find some help...


这篇关于从Javascript调用ASP.NET方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆