Ajax调用没有在.Net Web Forms App中遇到Server Side方法

时间:2016-08-19 22:29:43

标签: jquery asp.net ajax webforms

我有一个网络表单应用程序,通过单击按钮进行ajax调用:

$.ajax({
    type: 'GET',
    contentType: "application/json; charset=utf-8",
    url: 'Forum.aspx/TestMethod',
    async: false,
    success: function (response) {
        alert("SUCCESS");
    }
});

...在我的Forum.aspx.cs文件中使用此方法:

[WebMethod]
public static void TestMethod()
{
    Debug.Print("Hello");   
}

当我点击按钮时,我收到一条提示“成功”的提示,但是,它没有达到该方法。我已经将所有内容都删除到了上面看到的内容,并且我没有在VS'输出窗口中看到“Hello”(也没有遇到我设置的任何断点)。我在我的Page_Load方法中有一行显示Debug.Print("LOAD"),当我点击按钮时,我会在“输出”窗口中显示“LOAD”。所以,它正在使用Page_Load方法,而不是TestMethod我真正需要它来调用。

任何人都可以想到可能出错的任何事情吗?

3 个答案:

答案 0 :(得分:0)

搞定了!我的应用程序运行在.Net 2.0中。我重新配置了在4.0中运行的项目,现在它可以工作了。翻倒地狱......

答案 1 :(得分:0)

替换[WebMethod]

使用[WebMethod, System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]

您需要明确告诉Web方法使用HTTP GET。

如果您不想这样做,则可以选择其他选项。在$.ajax来电中,只需将type:'GET'更改为type:'POST'即可。

答案 2 :(得分:0)

不一定是您提出的问题,但如果您正在对驻留在常规Web表单页面中的服务器端方法进行JSON调用,那么您将采用“慢速路径”#34;。

我建议venv。与您的标准Web表单不同。没有页面生命周期(因此速度极快)和更清晰的代码分离以及可重用性。

在项目类型" Generic Handler"中添加一个新项目。这将创建一个新的.ashx文件。实现HttpHandler的任何类的主要方法是IHttpHandler。所以要使用原始问题中的代码:

ProcessRequest

更改AJAX调用中的url,应该这样做。 JavaScript看起来像这样,其中 RunTestMethod.ashx 是您刚刚创建的IHttpHandler的名称:

public void ProcessRequest (HttpContext context) {

    Debug.Print("Hello");   
    return;

    //the following code should be used to return json to the ajax method
    context.Response.ContentType = "text/json";
    context.Response.Write(json);
}

另一个需要考虑的小问题,如果您需要从Handler代码本身访问Session对象,请确保从$.ajax({ type: 'GET', //change this to POST if you want to pass a json object to the server side method (works in unison with the `dataType` property) contentType: "application/json; charset=utf-8", url: 'Handlers/RunTestMethod.ashx', async: true, //notice I set async to true so your page does not "freeze" while the ajax call is being made dataType: "json", //if needed, this property allows you to receive json back from the server side method (works in unison with the `type` property) success: function (response) { alert("SUCCESS"); } }); 接口继承:

IRequiresSessionState