简体   繁体   English

直接调用javascript function中的C#方法

[英]Call C# method in javascript function directly

How to call a c# method in javascript function directly.如何在 javascript function 中直接调用 c# 方法。 (eg page_load method of code behind page). (例如页面后面代码的page_load方法)。 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: 1-创建服务器端方法:

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).: 2- 实现System.Web.UI.IPostBackEventHandler.RaisePostBackEvent采用一个字符串参数(您可以将名称分配给此参数的值)。:

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

3- Write a script to trigger post back: 3-编写脚本以触发回发:

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

4- Call the PostBack trigger function when needed: 4- 需要时调用 PostBack 触发器 function:

<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.如果要调用 page_Load 事件,只需重新加载页面: window.location.reload()就会调用页面的加载事件。
  • If you want to do it with Asynchronously, you have to use XMLHttpRequest (that is to use an Ajax library).如果您想使用异步执行此操作,则必须使用 XMLHttpRequest(即使用 Ajax 库)。 You can use jQuery or Ajax.Net Professional or ASP.NET Ajax's update panel.您可以使用jQueryAjax.Net Professional或 ASP.NET Ajax 的更新面板。

I would use a web method, if you want to call a method in C# from JavaScript.如果您想从 JavaScript 调用 C# 中的方法,我将使用 web 方法。 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.NET - 以下 HTML 标记由 ASP.Net 文本框和 HTML 按钮组成。

<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. 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. TextBox 的值作为参数传递给 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. WebMethod - 以下 WebMethod 向用户返回问候消息以及当前服务器时间。 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.需要注意的重要一点是,该方法被声明为 static (C#),这是必要的,否则将不会从客户端 jQuery AJAX 调用调用该方法。

C# 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. javascript 是客户端,page_load 是服务器端。 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可能您可以仅为该方法创建一个单独的页面并通过 ajax 拨打电话

Simple answer: YOU CANNOT (at least page_load specifically).简单的答案:你不能(至少是 page_load)。 Get clear understanding about what is server-side and what is client side code.清楚地了解什么是服务器端代码和客户端代码。

Other options to call server side methods is using AJAX.调用服务器端方法的其他选项是使用 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.您可以创建一个ASHX 处理程序,在其中执行您要运行的 C# 方法,然后使用AJAX/jQuery调用该处理程序。

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.我不特别了解 c#,但是客户端与服务器端通信的一个好方法是通过RPC(远程过程调用)实现。
Lets say that you use JSON-RPC .假设您使用JSON-RPC
First, you create your json object that represents the request:首先,创建代表请求的 json object:

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

where the method represents the function name that you are calling,其中方法代表您正在调用的 function 名称,
the params represent an aray of parameters that the specified function should take, params表示指定的 function 应该采用的一系列参数,
and id is an unique identifier for requested objects. id是请求对象的唯一标识符。

Then you want to send this request to the server.然后你想将此请求发送到服务器。 This should be done with ajax.这应该使用 ajax 来完成。 Suppose you have a function that handles ajax requests called sendAjaxRequest that takes 3 parameters:假设您有一个 function 来处理名为sendAjaxRequest的 ajax 请求,该请求采用 3 个参数:

  1. the server-side targeted script服务器端目标脚本
  2. the request object请求 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:服务器接收请求,解释它并使用所需参数执行方法并构造响应 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.这是一个非常好的做法,无论情况如何。

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

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