Call C# method in javascript function directly

后端 未结 7 578
醉梦人生
醉梦人生 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:22

    You can create an ASHX handler where the C# method you want to run is executed and then use AJAX/jQuery to call the handler.

    0 讨论(0)
  • 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.

    <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
    <input id="btnGetTime" type="button" value="Show Current Time"
       onclick = "ShowCurrentTime()" />
    

    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.

    <script type = "text/javascript">
    
    function ShowCurrentTime() {
    $.ajax({
        type: "POST",
        url: "CS.aspx/GetCurrentTime", //Type name of your class here e.g student.aspx/Method
        data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response.d);
        }
    });
    }
    
    function OnSuccess(response) {
        alert(response.d);
    }
    
    </script>
    

    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();
    }
    
    0 讨论(0)
  • 2021-01-21 02:33

    Simple answer: YOU CANNOT (at least page_load specifically)! Get clear understanding about what is server-side and what is client side code.

    Other options to call server side methods is using AJAX! Read.

    0 讨论(0)
  • 2021-01-21 02:34

    javascript would be client side and page_load would be serverside . I don think you can call the method as such. May be you can create a separate page just for that method and make a call via ajax

    0 讨论(0)
  • 2021-01-21 02:37

    I don't know about c# in particular, but a good way for your client-side to comunicate with your server-side is through a RPC (Remote Procedure Call) implementation.
    Lets say that you use JSON-RPC.
    First, you create your json object that represents the request :

    var request = {
        "method": "echo", 
        "params": ["Hello JSON-RPC"],
        "id": 1
    }
    

    where the method represents the function name that you are calling,
    the params represent an aray of parameters that the specified function should take,
    and id is an unique identifier for requested objects.

    Then you want to send this request to the server. This should be done with ajax. Suppose you have a function that handles ajax requests called sendAjaxRequest that takes 3 parameters :

    1. the server-side targeted script
    2. the request object
    3. a callback to handle the response

      sendAjaxRequest(scriptUrl,request,function(response){
          alert("the server responded with : "+response.result);
      });
      

    The server recieves the request, interprets it and executes the method with the desired params and constructs a response json object :

    {
       "result": "Hello JSON-RPC", 
       "error": null, 
       "id": 1
    }
    

    and send it back to the client.

    This is a very good practice, no matter the situation.

    0 讨论(0)
  • 2021-01-21 02:46

    To call a server side method on a client side event you need to do the following:

    1- Create the server side method:

    void DoSomething(...) { ... }
    

    2- Implement the System.Web.UI.IPostBackEventHandler.RaisePostBackEvent which take one string argument (You can assign the name to the value of this argument).:

    public void RaisePostBackEvent(string eventArgument) 
    {
            DoSomething(...);
    }
    

    3- Write a script to trigger post back:

    function TriggerPostBack(control, arg){
        __doPostBack(control, arg);
    }
    

    4- Call the PostBack trigger function when needed:

    <a .... onclick="TriggerPostBack('control', 'arg')" .. /> 
    
    0 讨论(0)
提交回复
热议问题