Simple Caching of Partial Views in ASP.NET MVC 2

Posted Date: 6/22/2010 5:14:19 PM by Dan Martin

Caching of partial views in ASP.NET MVC can be a bit tricky. If you use Html.RenderAction() to display your cached partial view, you will find that not only is the partial view cached but the rest of the view page is as well. Not quite what we are trying to achieve… Given the way the [OutputCache] filter is implemented, it is a wrapper around the core ASP.NET output caching; it isn’t surprising that we run into these sorts of problems.

Any Workarounds?

Thankfully, others have figured out some workarounds to make caching of partial views possible. Steve Sanderson blogged about a solution where you create a custom output caching filter. Phil Haack posted another solution here as well. (Note: these solutions are for MVC 1, but you should be able to apply them to MVC 2 as well.)

MVC Futures Can Help

You will be happy to hear that there is an even easier solution if you are using ASP.NET MVC 2 and are able to use the MVC futures assembly. Simply add the Microsoft.Web.Mvc.Aspnet4.dll to your project and you can use the new [ChildActionCache] filter on the action method:

 

    public class LinkController : Controller

    {

        [ChildActionCache(Duration = 300)]

        public ViewResult Links()

        {

            ViewData["currentTime"] = DateTime.Now;

            return View();

        }

    }

 

Now your partial view will be cached for the desired duration (in seconds), but the rest of the view will load as normal.

Not a fan of either solution? Well if it helps, improved caching support is listed as an area of focus for ASP.NET MVC 3. The roadmap says: “Improved Caching Support – Enable caching of an child action when called via the RenderAction method. Also looking at donut caching and donut hole caching.”

Conclusion

So you have several options for caching your partial views right now, and improved caching support is on the way. Hope this is helpful.

blog comments powered by Disqus