开发者

Request.IsAjaxRequest not working properly in asp.net mvc2

I'm using asp.net mvc2 for my application. I have an ajax request sent using jQuery.

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

Here is my controller method

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
   }
}
开发者_StackOverflow

In index actionresult Request.IsAjaxRequest() works properly but when its redirected to List actionresult it does not identify it as ajax request. how can I know that list is being called from an ajax redirection?

Edit

Request.IsAjaxRequest is returning true in IE for both index and List methods while in firefox Request.IsAjaxRequest is true only for index method. When I inspect the code for ajax request I could see two of them; first is post to index method and second is Get from List method. IE sends x-requested-with header with both requests while Firefox is sending this header only for first request destined to index method.

How can I make Firefox work like IE (in this scenario only) i.e sending x-requested-with header with both request in case when second request is not originated from client but is a redirection from first request.


muhammad,

you should do something like this in your index action:

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  
}

should work as planned i'd think, as long as you had a partialview called List that had a strongly typed class matching the items being passed in.


I have done something like

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜