简体   繁体   English

如何在特定时间从javascript调用C#中的函数

[英]How to call function in C# from javascript at particular time

<script type="text/javascript">
   var startTime = new Date();
   var TimeTaken;
        //Start the clock!
   window.onbeforeunload = function ()        
   {
       var endTime = new Date();
       //Get the current time.
       var timeSpent = (endTime - startTime);
       seconds = (timeSpent / 1000) % 60;
       TimeTaken = parseInt(seconds);
       //return TimeTaken;
       var temp = document.getElementById('<%=Label1.ClientID %>').value;
       temp = TimeTaken;
       alert(temp);
         <%PageO(); %>
  };

The above JS file runs when I close the tab/page in browser. 当我关闭浏览器中的选项卡/页面时,上面的JS文件就会运行。 But the function Which I called <%PageO(); %> 但是我叫<%PageO(); %>的函数<%PageO(); %> <%PageO(); %> executes when the programs starts running itself. 当程序开始自行运行时,将执行<%PageO(); %> This function call in code behind(C#) should execute only when the tab/page is closed not at the start of the program. 仅在关闭选项卡/页面时(而不是在程序开始时),才应执行后面(C#)代码中的此函数调用。

Any mistakes in this code? 这段代码有任何错误吗?

Try This - You have to use PageMethods 试试看 -您必须使用PageMethods

<script type="text/javascript">
var startTime = new Date();
   var TimeTaken;
        //Start the clock!
   window.onbeforeunload = function ()        
   {
       var endTime = new Date();
       //Get the current time.
       var timeSpent = (endTime - startTime);
       seconds = (timeSpent / 1000) % 60;
       TimeTaken = parseInt(seconds);
       //return TimeTaken;
       var temp = document.getElementById('<%=Label1.ClientID %>').value;
       temp = TimeTaken;
       alert(temp);
       // USE PAGEMETHODS FOR CODE BEHIND METHOD CALL
         PageMethods.PageO(function (response) {                 
        alert(response);
    });
  };
</script>
  • And you have to add ScriptManager in your .aspx page as below 并且您必须在.aspx页中添加ScriptManager ,如下所示

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

  • And in .aspx.cs file your Method with WebMethod as below 然后在.aspx.cs文件中,使用WebMethod的方法如下所示

    ` `

    [System.Web.Services.WebMethod]

     public static string PageO() { return "Yes this is working"; } 

    ` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM