没有调用页面方法

时间:2011-05-19 09:36:36

标签: c# .net asp.net jquery

我设置了一个页面方法,并尝试通过jQuery调用它。有时我到成功函数,有时候到错误函数,对我来说似乎是随机的。在任何情况下,响应都包含整个页面标记。

我尝试使用$.ajaxScriptManager同样的结果。 我也在这里尝试了这个想法:Call ASP.NET PageMethod/WebMethod with jQuery - returns whole page而没有。

以下是JavaScript代码:

$(document).ready(function() {
    $(".tree").dynatree({
        onActivate: function(node) {
            $('#title').val(node.data.title);
            $.ajax({
                type: "POST",
                url: window.location.href + "/GetData",
                data: "{'ID':22}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) { alert(response); },
                error: function() { alert('Error!'); }
            });
        }
    });
});

这是c#代码:

[WebMethod]
public static string GetData(string ID)
{
    if (string.IsNullOrEmpty(ID))
        throw new Exception("No ID passed!");
    return "Test";
}

编辑嗯,我搞定了。我将参数类型从int更改为string,现在调用该方法。我可以稍后做int.Parse,但为什么会这样呢?

2 个答案:

答案 0 :(得分:1)

正在发生的事情是,在jQuery调用中将数据设置为{}是相当于将其设置为NULL的JSON。在这种情况下,没有webmethod接受null并且调用失败。

答案 1 :(得分:0)

我在我当前的应用程序中做了一些非常相似的事情,唯一的区别是我在ajax调用中有以下额外选项:

beforeSend: function(xhr) { xhr.setRequestHeader("Content-type", "application/json; charset=utf-8"); }

希望有帮助...