Call C# method in javascript function directly

后端 未结 7 657
醉梦人生
醉梦人生 2021-01-21 02:10

How to call a c# method in javascript function directly. (eg page_load method of code behind page). Please help me.

7条回答
  •  我在风中等你
    2021-01-21 02:32

    I would use a web method, if you want to call a method in C# from JavaScript. An example is provided below. I hope this is of some help.

    ASP.NET - The following HTML Markup consists of an ASP.Net TextBox and an HTML Button.

    
    
    

    JavaScript Code: - When the Button is clicked the ShowCurrentTime JavaScript function is executed which makes an AJAX call to the GetCurrentTime WebMethod. The value of the TextBox is passed as parameter to the WebMethod.

    
    

    The WebMethod - The following WebMethod returns a greeting message to the user along with the current server time. An important thing to note is that the method is declared as static (C#), this is necessary otherwise the method will not be called from client side jQuery AJAX call.

    C#

    [System.Web.Services.WebMethod]
    public static string GetCurrentTime(string name)
    {
        return "Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
    }
    

提交回复
热议问题