2010-12-08 58 views

回答

43

你可以多建立自己的擴展方法一樣MVC code

例如

public static bool IsAjaxRequest(this HttpRequest request) 
{ 
    if (request == null) 
    { 
     throw new ArgumentNullException("request"); 
    } 

    return (request["X-Requested-With"] == "XMLHttpRequest") || ((request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest")); 
} 

HTHS,
查爾斯

編輯:其實回調的要求也Ajax請求,

public static bool IsAjaxRequest(this HttpRequest request) 
    { 
     if (request == null) 
     { 
      throw new ArgumentNullException("request"); 
     } 
     var context = HttpContext.Current; 
     var isCallbackRequest = false;// callback requests are ajax requests 
     if (context != null && context.CurrentHandler != null && context.CurrentHandler is System.Web.UI.Page) 
     { 
      isCallbackRequest = ((System.Web.UI.Page)context.CurrentHandler).IsCallback; 
     } 
     return isCallbackRequest || (request["X-Requested-With"] == "XMLHttpRequest") || (request.Headers["X-Requested-With"] == "XMLHttpRequest"); 
    } 
1

通常,您需要測試X-Requested-With標頭,確保其值爲'XMLHttpRequest'。我不是一個C#開發人員(還),但快速谷歌搜索說,在C#它是這樣的:

Request.Headers["X-Requested-With"] == "XMLHttpRequest"; 
4

嘗試檢查的ScriptManager IsInAsyncPostBack

ScriptManager.GetCurrent(Page).IsInAsyncPostBack 
+0

這是否工作,它們都從jQuery的阿賈克斯以及來自諸如更新面板控件觸發Ajax請求? – DotnetDude 2010-12-08 22:14:59

+1

我不確定,所以我寫了`try` ;-) – 2010-12-08 22:17:03

1

是, Request.IsAjaxRequest看着標題和X-Requested-With查詢字符串,但它似乎你的jQuery不發送X-Requested-With標題。

你可以試試,看看郵件頭。它是通過使用招,或者只發送發送的查詢字符串通過設置POST網址

/whatever.aspx?x-requested-with=XMLHttpRequest

+0

JQuery發送了X-Requested-With,所以如果我檢查每個Karim79的頭文件,它就會起作用。但是,Request在基本頁面中沒有IsAjaxRequest屬性。 – DotnetDude 2010-12-08 22:34:31

0

裝飾你的類[WebMethod(EnableSession = true)]語法,如果你寫的代碼下面的函數一樣在ajax調用後面並調用相同的函數,您可以確定。

[WebMethod(EnableSession = true)] 
    public static void getData(string JSONFirstData,string JSONSecondData, string JSONThirdData, string JSONForthData, ...) 
    { 
     //code 
    } 
在阿賈克斯URL

URL :'/Codebehind.aspx/getData'

相關問題