2016-08-19 35 views
0

我有一個Web窗體應用程序中調用Ajax正在通過點擊一個按鈕做: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

任何人都可以想到任何可能是錯誤的?

+0

如果返回從TestMethod的一個字符串並傳遞給函數成功的響應包含字符串? – Calum

+0

@Calum - 不,如果在我的成功函數中,我會說「alert(response);,;」我得到了實際頁面的HTML。我的假設是,這是因爲它給了我「Page_Load」的「響應」而不是「TestMethod」。 – Hill

回答

0

拼圖出來!我的應用程序在.Net 2.0中運行。我將項目重新配置爲在4.0中運行,現在可以運行。翻轉地獄......

0

更換[WebMethod]

隨着[WebMethod, System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]

你需要明確地告訴使用HTTP GET Web方法。

如果你不想這樣做,你有另一種選擇。在$.ajax調用簡單地改變type:'GET'type:'POST' - 這也將工作。

0

不一定是您要問的問題,但如果您正在對駐留在常規Web表單頁面中的服務器端方法執行JSON調用,那麼您正在採用「緩慢的道路」。我會建議HttpHandler。不像你的標準網頁表單。沒有頁面生命週期(所以它快速發展),更簡潔的代碼分離以及可重用性。

將新項目添加到「Generic Handler」類型的項目中。這將創建一個新的.ashx文件。執行IHttpHandler的任何類的主要方法是ProcessRequest。所以要使用您的原始問題的代碼:

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); 
} 

更改您的AJAX調用中的網址,應該這樣做。 JavaScript的應該是這樣的,在那裏RunTestMethod.ashx是剛剛創建了IHttpHandler的名字:

$.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"); 
    } 
}); 

另一個小一點來考慮,如果你需要從處理程序代碼本身內訪問Session對象,確保從IRequiresSessionState接口繼承:

public class GetFileHandler : IHttpHandler, IRequiresSessionState