Disable browser cache for ajax request on ASP.NET MVC

The application reloads the list of jobs, if any job is reposted or expired. We display different labels, such as “reposted”, “expired”, depending on the action. It worked well with browsers but IE 8.

Simply, IE was cacheing the part of html. Though we request the partial view by post.

update: function () {
    $.ajax({
        type: "GET",
        url: "MJobsB?p=" + list.cPg(),
        contentType: "text/html; charset=utf-8",
        dataType: "html",
        success: function (data) {
            $('#ct #cnt').html(data);
        },
        error: function () { alert("Error Loading Jobs"); }
    });
},

So, we brought in NoCache attribute. And made the action not cached on IE. We made it with attribute, as we want to cache other stuff, especially images.

This is NoCache attribute.

public class NoCacheAttribute : ActionFilterAttribute
{
    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
        filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
        filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
        filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        filterContext.HttpContext.Response.Cache.SetNoStore();

        base.OnResultExecuting(filterContext);
    }
}

On controller, you just add the attribute.

[NoCache]
[HttpGet]
public ActionResult MJobsB(int cId, int? pg)
{
    return RenderJobListIn("_MJobsB", cId, Mode.List, pg, false);            
}
Disable browser cache for ajax request on ASP.NET MVC

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s