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

时间:2021-09-18 16:24:12

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?

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

8 个解决方案

#1


16  

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.ScriptSerive]装饰,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中找到的例子。

#2


7  

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;
        .....
        .....
    }
}

#3


1  

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服务。此功能仅适用于同一页面上的静态方法。

#4


1  

C#

C#

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

JS/jQuery

JS / jQuery的

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

#5


0  

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>

#6


0  

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中读取它。

#7


-1  

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

#8


-4  

Dave has 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从客户端调用页面方法。一般的想法是这样的(如果你发现任何问题请参考戴夫的网站)。

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

#1


16  

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.ScriptSerive]装饰,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中找到的例子。

#2


7  

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;
        .....
        .....
    }
}

#3


1  

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服务。此功能仅适用于同一页面上的静态方法。

#4


1  

C#

C#

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

JS/jQuery

JS / jQuery的

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

#5


0  

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>

#6


0  

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中读取它。

#7


-1  

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

#8


-4  

Dave has 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从客户端调用页面方法。一般的想法是这样的(如果你发现任何问题请参考戴夫的网站)。

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