2011-05-19 70 views
1

我设置了一个页面方法,并试图通过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更改为字符串,现在调用该方法。我可以稍后再做int.Parse,但为什么会发生这种情况?

+0

当你使用生成的客户端代理它是否工作(即PageMethods.GetData(...)?) – davidfowl 2011-05-19 09:45:47

+0

@dfowler - Nope。同样的结果。 – 2011-05-19 09:47:23

+0

你的路线或任何可能与网址混淆? – davidfowl 2011-05-19 10:34:45

回答

1

发生什么事是在jQuery调用中将数据设置为{}是将其设置为NULL的JSON等效项。在这种情况下,不存在接受null且调用失败的webmethod。

+0

对不起。我更新了正确版本的帖子(带参数) – 2011-05-19 13:24:58

+0

您的回答指出我的方向正确。之前我有:data:“{'ID':'22'}”,所以asp.net正在寻找一个参数类型为string的方法。一旦我删除了' - 一切开始工作。谢谢! – 2011-05-19 13:58:53

+0

啊,这是有道理的。很高兴有帮助。 – Lester 2011-05-19 14:06:09

0

我做我的当前应用程序,我可以看到的唯一区别非常类似的是,我在我的Ajax调用以下额外的选项:

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

希望帮助...