代码之家  ›  专栏  ›  技术社区  ›  Muhammad Adeel Zahid

在asp.net mvc2中,Request.IsAjaxRequest无法正常工作

  •  1
  • Muhammad Adeel Zahid  · 技术社区  · 15 年前

    $.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()中工作正常,但当其重定向到List actionresult时,它不会将其标识为ajax请求。我怎么知道列表是从ajax重定向调用的?
    编辑1: Request.IsAjaxRequest在IE中为index和List方法返回true,而在firefox中为Request.IsAjaxRequest仅为index方法返回true。当我检查ajax请求的代码时,我可以看到其中两个:第一个是post to index方法,第二个是Get from List方法。IE发送带有两个请求的x-requested-with头,而firefox只为第一个发送到index方法的请求发送此头。如果第二个请求不是来自客户端,而是来自第一个请求的重定向,那么如何使firefox像i e一样工作(仅在本场景中),即使用两个请求发送x-requested-with-header。
    谢谢

    2 回复  |  直到 15 年前
        1
  •  1
  •   jim tollan    15 年前

    穆罕默德,

    您应该在索引操作中执行以下操作:

    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  
    }
    

        2
  •  0
  •   halfer    7 年前

    我做了一些类似的事情

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