2011-05-19 80 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"); } 

希望幫助...