Thursday, June 7, 2012

Internet explorer and AJAX caching headache in MVC

Spent several hours figuring our what was going wrong with my ajax calls. After the initial ajax call to a controller method that returns a JSONResult, the subsequent calls weren't even hitting the controller code. This was working fine in Chrome all along.

To fix this I had to create an ActionFilter attribute to specify no caching for httpgets. This post solved my problem - http://stackoverflow.com/questions/2027610/asp-net-mvc-2-rc-caching-problem

public class CacheControlAttribute : System.Web.Mvc.ActionFilterAttribute
    {
        public CacheControlAttribute(HttpCacheability cacheability)
        {
            this._cacheability = cacheability;
        }

        private HttpCacheability _cacheability;

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
            cache.SetCacheability(_cacheability);
        }
    } 

//in the controller
 [CacheControl(HttpCacheability.NoCache),HttpGet]
        public JsonResult GetUpcomingMatches(Guid id, int divisionId)
        {
            var reply = m_matchLogic.GetUpcomingMatches(id, divisionId);
            return Json(reply, JsonRequestBehavior.AllowGet);
        }

No comments:

Post a Comment