在ASP.NET Web窗体中,如何使用"get"请求调用页面方法

BAL*_*GAN 9 c# asp.net ajax

在ASP.NET Web窗体中,我能够使用Ajax"post"请求调用页面方法.但我无法使用"获取请求"调用页面方法.

在这种情况下,是否可以使用"获取"请求调用页面方法.您能否提供任何建议?页面方法的示例代码:

    [WebMethod]
    public static string GetData()
    {            
        return "test";
    }
Run Code Online (Sandbox Code Playgroud)

Izz*_*zzy 11

作为@vc在评论中提到的,您需要使用的ScriptMethodAttribute,以及WebMethod因为你希望你的要求是GETPOST那么改变你的代码如下:

[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetData()
{
   return "test";
}
Run Code Online (Sandbox Code Playgroud)

在标记中你可以做到

function ShowTestMessage() {
     $.ajax({
          type: "GET",
          url: "YourPage.aspx/GetData",
          data: {},
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function (response) {
        alert(response.d);
    }
});
}
function OnSuccess(response) {
alert(response.d);
}

<input id="ButtonId" type="button" value="Show Message"
onclick = "ShowTestMessage()" />
Run Code Online (Sandbox Code Playgroud)

不要忘记添加以下参考

using System.Web.Script.Services;
using System.Web.Services;
Run Code Online (Sandbox Code Playgroud)