C# 使用 JavsScript 从客户端调用服务器端的非静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1360253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:37:20  来源:igfitidea点击:

Call non-static method in server-side from client-side using JavsScript

c#asp.netasmxwebmethod

提问by Pramulia

How do I call a non-static method in server side(aspx.cs) from client side using javascript (aspx)....?

如何使用javascript(aspx)从客户端调用服务器端(aspx.cs)中的非静态方法...?

As far as I know I can call static method in server side from client side...

据我所知,我可以从客户端调用服务器端的静态方法......

server side:

服务器端:

 [WebMethod]
 public static void method1()
 {
 }

client side:

客户端:

 <script language="JavaScript">
     function keyUP() 
     {
         PageMethods.method1();
     }
 </script>
 <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
 </asp:ScriptManager>

It works. Now how do I call non-static method from client side?

有用。现在如何从客户端调用非静态方法?

回答by TheVillageIdiot

No you cannot call non-static methods from client side per se. I've tried it once but it is ugly one (also I used jQuery ajax). Just call the page using ajax with method name appended to it as query string parameter and then on server side check the parameter and call the relevant method. But as I've told you it is pretty ugly :(

不,您不能从客户端本身调用非静态方法。我试过一次,但它很丑(我也用过 jQuery ajax)。只需使用 ajax 调用页面,并附加方法名称作为查询字符串参数,然后在服务器端检查参数并调用相关方法。但正如我告诉你的那样,它非常丑陋:(

$.ajax({'/mypage.aspx?m=mymethod',......}); //this is not correct syntax

on server side:

在服务器端:

protected void Page_Load(object sender, EventArgs e)
{
    if(!Request.QueryString.HasKeys() || 
                string.IsNullOrEmpty(Request.QueryString["m"]))
    {
        //return error or something relevant to your code
    }
    var m = Request.QueryString["m"];

    switch(m)
    {
        case "a":
        a();
        break;
        .....
        .....
    }
}

回答by John Saunders

Actually, you don't get to call non-static methods in this way.

实际上,您无法以这种方式调用非静态方法。

When you are calling a PageMethod, you're basically calling a special web service. This feature only works with static methods on the same page.

当您调用 PageMethod 时,您基本上是在调用特殊的 Web 服务。此功能仅适用于同一页面上的静态方法。

回答by TheVillageIdiot

Davehas written in detail about calling page methods from client side using jquery ajax. The general idea is like this (if you find any problem please refer to Dave's site).

Dave详细介绍了使用 jquery ajax 从客户端调用页面方法。大体思路是这样的(如果你发现任何问题,请参考 Dave 的网站)。

C# Code:

C# 代码:

[WebMethod]
public static string yourmethod(/*params*/)
{
   return "Hello World!"   
}

ASPX:

ASPX:

$.ajax({
    type: 'POST',
    data: /*Your Data*/,
    dataType: 'JSON',
    contentType: 'application/json',
    url: '/yourpage.aspx/yourmethod',//Method to call
    success: function(result, status) {
        //handle return data
    },
    error: function(xhr, status, error) {
        //handle error
    }
});

回答by Kubi

as an answer to Pramulia i think you want to have a function with an argument from the client side which is implemented in the example -> CallServer(arg1, arg2)

作为对 Pramulia 的回答,我认为您想要一个带有来自客户端的参数的函数,该函数在示例中实现 -> CallServer(arg1, arg2)

<%@ Page Language="C#" AutoEventWireup="true"  %>
<%@ Implements Interface="System.Web.UI.ICallbackEventHandler" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html >
<head runat="server">
    <title>Client Callbacks</title>
    <script runat="server">
        public void RaiseCallbackEvent(String eventArgument)
        {
            // Processes a callback event on the server using the event
            // argument from the client.
        }

        public string GetCallbackResult()
        {
            // Returns the results of a callback event to the client.
            string dateString = DateTime.Now.ToLongDateString();

            return dateString;
        }

        void Page_Load(object sender, EventArgs e)
        {
            ClientScriptManager cm = Page.ClientScript;
            String cbReference = cm.GetCallbackEventReference(this, "arg",
                "ReceiveServerData", "");
            String callbackScript = "function CallServer(arg, context) {" +
                cbReference + "; }";
            cm.RegisterClientScriptBlock(this.GetType(),
                "CallServer", callbackScript, true);
        }
    </script>
    <script type="text/javascript">
        function ReceiveServerData(arg, context) {
            Message.innerText = "Date from server: " + arg;
        }
    </script>
</head>
<body>
    <h2>Client Callbacks Without Postbacks</h2>
    <form id="form1" runat="server">
       <input type="button" value="Callback" 
           onclick="CallServer('1', alert('Callback sent to Server'))" />
       <br />
       <span id="Message"></span>
   </form>
</body>
</html>

回答by shawn deutch

You can avoid the static constraint by using a simple .asmx page instead of the codebehind page.

您可以通过使用简单的 .asmx 页面而不是代码隐藏页面来避免静态约束。

1) Open New Website using the AJAX Enable ASP.NET template (it puts the necessary references in the web.config)

1) 使用 AJAX Enable ASP.NET 模板打开新网站(它将必要的引用放在 web.config 中)

2) SIMPLESERVICE.ASMX - Add a new .asmx web service (I called mine SimpleService.asmx) Notice the [System.Web.Script.Services.ScriptSerive] decoration and that the SimpleService class implements Webservice.

2) SIMPLESERVICE.ASMX - 添加一个新的 .asmx Web 服务(我称之为 SimpleService.asmx) 注意 [System.Web.Script.Services.ScriptServe] 装饰和 SimpleService 类实现 Webservice。

<%@ WebService Language="C#" Class="SimpleService" %>

using System;
using System.Web.Services;

[System.Web.Script.Services.ScriptService]
public class SimpleService : WebService
{
    [WebMethod]
    public string GetMessage(string name)
    {
        return "Hello <strong>" + name + "</strong>, the time here is: " + DateTime.Now.ToShortTimeString();
    }
} 

3) DEFAULT.ASPX - To use it reference the service in you script manager and you are off and running. In my Javascript I call the class.method - SimpleService.GetMessage.

3) DEFAULT.ASPX - 要使用它引用脚本管理器中的服务,并且您已关闭并正在运行。在我的 Javascript 中,我调用 class.method - SimpleService.GetMessage。

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
     <script language="javascript" type="text/javascript">       
        function callServer() {
            SimpleService.GetMessage($get("Name").value, displayMessageCallback);
        }

        function displayMessageCallback(result) {
            $get("message").innerHTML = result;
        } 
    </script>


</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" >
            <Services>
                <asp:ServiceReference Path="~/SimpleService.asmx" />
            </Services>
        </asp:ScriptManager>
        <div>
        </div>
        <h1>Hello World Example</h1>

        <div>
            Enter Name: <input id="Name" type="text" />

            <a href="javascript:callServer()">Call Server</a>

            <div id="message"></div>
        </div>  
    </form>
</body>
</html>

I used the example I found from Scott Gu Found Here.

我使用了从 Scott Gu Found Here 中找到的示例

回答by Mike

C#

C#

public string LoadString() {
    return "my string";
}

JS/jQuery

JS/jQuery

$('#txt').val(<%= LoadString() %>);

回答by Manoj Bhardwaj

If you want to call it using the same function, you can use the following code:

如果要使用相同的函数调用它,可以使用以下代码:

[WebMethod]
public static void method1()
{
    ClassOfNonStaticFunction obj = new ClassOfNonStaticFunction();
    obj.yourFunctionName(ParametersIfAny);
}

回答by Bbb

I ended up using hidden fields in case anyone reads this. I can set the value in c# under a function and then read it in javascript.

我最终使用了隐藏字段,以防有人读到这个。我可以在函数下的 c# 中设置值,然后在 javascript 中读取它。