Partial View Caching in ASP.NET MVC 3
Posted Date: 6/23/2011 2:19:07 AM by Dan Martin
Exactly one year ago I wrote a post on how to cache partial views in ASP.NET MVC 2. Back then, you had to make use of the futures assembly to get this functionality but it was marked as being planned for version 3. I figured I’d write an update post to go over partial view caching and how it has been implemented in ASP.NET MVC 3. As expected, it is now part of the main project and does not require any additional assemblies or packages to be used.
In version 2, the MVC futures assembly had a ChildActionCache attribute that one could use to achieve this functionality. However, in ASP.NET MVC 3 you can now simply use the OutputCache attribute with the child action, just as you normally would with any regular action.
public class TimeController : Controller
{
[ChildActionOnly]
[OutputCache(Duration = 600)]
public PartialViewResult Index()
{
ViewBag.CurrentTime = DateTime.Now;
return PartialView();
}
}
The duration is in seconds, so in the code above we are telling ASP.NET MVC to cache this child action for 10 minutes. Now when we use this partial view within a regular view, the output will be cached for the specified duration regardless if the main view is cached or not.
This can be very helpful in some cases. For example, I use partial views for my Links section and the archive links to the right of the page. That data does not change very often, so I cache the child actions to prevent that same data from being retrieved over and over. Hope you find this helpful.
blog comments powered by Disqus

