views:

288

answers:

1

I use ajaxForm with jQuery, and there's one problem with Firefox - for some reason it does not preserve X-Requested-With custom header (which is used to detect IsAjaxRequest()). This leads to my controller action returning full view instead of partial since IsAjasxRequest() returns false after redirect.

This bug only happens in Firefox, it works fine in Chrome for example.

You can see this bug mentioned here. A pretty old post so I wonder why it still happens to me (I use Firefox 3.5.3). Anyway, here's the solution I invented - in my base controller class:

  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
     var ajaxRequestBeforeRedirect = TempData["__isajaxrequest"] as string;
     if (ajaxRequestBeforeRedirect != null)
        Request.Headers.Add("X-Requested-With", ajaxRequestBeforeRedirect);
  }

  private bool IsRedirectResult(ActionResult result)
  {
     return result.GetType().Name.ToLower().Contains("redirect");
  }

  protected override void OnActionExecuted(ActionExecutedContext filterContext)
  {
     base.OnActionExecuted(filterContext);
     if (IsRedirectResult(filterContext.Result) && Request.Headers["X-Requested-With"] != null)
        TempData["__isajaxrequest"] = Request.Headers["X-Requested-With"];
  }

It works; however, I have two questions here:

  1. Is this bug really not fixed in Firefox or I don't understand something?
  2. Is it a good solution? Is there any better? I can't believe noone had this issue before.

UPDATE: for those who is interested in this issue, Request.Headers.Add has problems with IIS6 (or maybe IIS5, but anyway). So the correct way would be to store this "isAjaxRequest" flag in TempData/HttpContext.Items/base controller.

+2  A: 

Just in case somebody else stumbles on this question after wondering why their header-based dispatching fails in Firefox, this is not fixed as of 2010-10-11, tested in Firefox 3.6.10

https://bugzilla.mozilla.org/show_bug.cgi?id=553888 is the corresponding bug, and from the latest comments as of today (by Jonas, made on 2010-09-16) this issue will not be fixed in Firefox 4.

Furthermore, this bug seems to extend to standard settable headers such as Accept, meaning an Accept: application/json will disappear after a redirect and your xhr engine will very likely get an HTML response instead.

Masklinn