简体   繁体   中英

Call C# method in javascript function directly

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

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')" .. /> 

You have multiple choices and each choice has its own pros and cons.

  • If you want to call page_Load event, just reload the page: window.location.reload() and the load event of your page will be called.
  • If you want to do it with Asynchronously, you have to use XMLHttpRequest (that is to use an Ajax library). You can use jQuery or Ajax.Net Professional or ASP.NET Ajax's update panel.

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

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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