Ajax方法外部类

时间:2015-08-14 10:30:32

标签: c# jquery ajax

继续使用此解决方案https://stackoverflow.com/a/4508430/1622376

我正在尝试修改它以通过以下方式使用外部类中的sayhello方法:

Example2.aspx

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Services" %>
<%@ Register Assembly="MyClasses" Namespace="MyClasses" TagPrefix="test" %>


<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<test:Ajax2 runat="server" />

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(function () {
                $.ajax({
                    type: 'POST',
                    url: 'Example2.aspx/sayhello',
                    data: JSON.stringify({ name: 'Scott' }),
                    contentType: 'application/json; charset=utf-8',
                    dataType: 'json',
                    success: function (msg) {
                        // Notice that msg.d is used to retrieve the result object
                        alert(msg.d);
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert(xhr.responseText);
                        alert(thrownError);
                    }
                });
            });
        }); 
    </script>

</body>
</html>

然后我的班级用sayhello方法是:

using System;
using System.Web;
using System.Text;

namespace MyClasses
{

    public class Ajax2 : System.Web.UI.Page
    {

        public static string SayHello(string name)
        {
            return "Hello " + name;
        }

    }

}

我添加了一个ajax错误功能,以提供有关请求失败原因的一些信息:

<title>Unknown web method sayhello.<br>Parameter name: methodName</title>

[ArgumentException: Unknown web method sayhello.

Parameter name: methodName]

   System.Web.Script.Services.WebServiceData.GetMethodData(String methodName) +488515

   System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs eventArgs) +162

   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136

   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +69

我正在尝试做甚么可能吗?

2 个答案:

答案 0 :(得分:0)

您必须注释您的方法,以便编译器知道它是一个PageMethod,因此可以从jQuery访问。

[System.Web.Services.WebMethod]
public static string SayHello(string name) { ... }

转换为asmx网络服务:

[System.Web.Script.Services.ScriptService]
public class Ajax2 : System.Web.Services.WebService
{
    [WebMethod]
    public string SayHello(string name)
    {
        return "Hello " + name; 
    }
}

答案 1 :(得分:0)

当您想要使用Ajax调用调用支持方法时,您必须使 [WebMethod]

  [WebMethod]
  public static string SayHello(string name)
        {
            return "Hello " + name;
        }