2010-11-11 19 views
1

我使用asp.net mvc2作爲我的應用程序。我有一個使用jQuery發送的ajax請求。Request.IsAjaxRequest在asp.net中無法正常工作mvc2

$.ajax{(
url:'/home/index' 
type:'post', 
data:$('#myform').serialize(), 
dataType:'html', 
success:function(response) 
{ 
    //update relevent document portion 
} 
}); 

這裏是我的控制器方法

public ActionResult index(Book book) 
{ 
    Repository _repo = new Repository(); 
    _repo.Add(book); 
    _repo.Save(); 
    if(Request.IsAjaxRequest()) 
    { 
     return RedirectToAction("List",new{id=book.id}); 
    } 
    //do something else 
} 

public ActionResult List(int id) 
{ 
    if(Request.IsAjaxRequest())/* here it always returns false even though its been redirected from an ajax request to get here*/ 
    { 
     //do something 
    } 
} 

在指數的ActionResult Request.IsAjaxRequest()正常工作,但是當其重定向到列出的ActionResult它不識別爲Ajax請求。我怎麼知道這個列表是從ajax重定向調用的?
Edit1: Request.IsAjaxRequest在IE中爲index和List方法返回true,而在firefox中Request.IsAjaxRequest僅在索引方法中爲true。當我檢查ajax請求的代碼時,我可以看到其中兩個;首先是索引方法,第二是Get方法。 IE向這兩個請求發送x-requested-header,而firefox只在第一個請求發送給index方法時發送這個頭。我怎麼能讓IE瀏覽器像IE一樣工作(僅在這種情況下),例如,當第二個請求不是從客戶端發起,而是從第一個請求重定向的情況下,發送x請求 - 帶有兩個請求的頭部。
感謝

+0

它不會烏爾工作。因爲再重定向到另一個動作中,我想傳達它將作爲簡單redirect.what那麼你的Jquery ajax post只能用於索引操作。你可以使用一個標誌變量來做到這一點。只需在索引操作下在Request.IsAjaxRequest()中設置標誌狀態並在列表中檢查它。 – 2010-11-11 12:22:56

+0

@plz c問題更新 – 2010-11-12 04:43:03

回答

0

好的,我做了一些像

public ActionResult index(Book book) 
{ 
    Repository _repo = new Repository(); 
    _repo.Add(book); 
    _repo.Save(); 
    if(Request.IsAjaxRequest()) 
    { 
     return List(book.id); 
    } 
    //do something else 
} 

public ActionResult List(int id) 
{ 
    if(Request.IsAjaxRequest())/* in this scenario Request.IsAjaxRequest returns true because there is no redirection and no new request*/ 
    { 
     return View("List"); 
    } 
} 

現在我想知道是否有一些問題,這種方法
問候

1

穆罕默德,

你應該做這樣的事情在你的索引行動:

public ActionResult index(Book book) 
{ 
    Repository _repo = new Repository(); 
    _repo.Add(book); 
    _repo.Save(); 
    var items = _repo.GetItems(book.id); 
    if(Request.IsAjaxRequest()) 
    { 
     return PartialView("List", items); 
    } 
    //do something else 
} 

應該工作按計劃我倒是覺得,只要你有一個叫partialview列表有一個強類型匹配的項目被傳入英寸

+0

hey jim可以請您詳細解釋一下「PartialView」。我的意思是它基本上是如何工作的。感謝 – 2010-11-11 12:34:00

+0

當然。如果您使用與項目匹配的強類型模型創建partialview,那麼partialview只會更新您的ajax調用中成功函數所針對的頁面部分。你可以通過下載一個我昨天爲另一個問題創建的小應用程序來看到這個實例。它在這裏:http://www.gatehousemusic.com/downloads/MvcApplication2.zip – 2010-11-11 12:40:47

+0

okkk ya.i有你。感謝一個吉姆。感謝樣本好友... – 2010-11-11 12:47:06

相關問題