Search code examples
asp.net-mvcasp.net-mvc-3razorrenderpartial

MVC3 RenderPartial caching across multiple pages


Can anyone tell me if its possible to Cache a RenderPartial across multiple pages? I have a RenderPartial for a user profile that shouldn't really ever change unless the user updates their profile. So i dont really want to go back and get his/her profile every time i load a page. I would much rather pass the partial around until im forced to update (i.e. profile update)

I looked at the DonutHole example that p.haack put together, but it seems to be relevant for a single page. Can someone point me in the right direction or offer any advice? Or am i only able to cache one page at a time? thanks!


Solution

  • You could use RenderAction instead. Example:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    
        public ActionResult About()
        {
            return View();
        }
    
        [OutputCache(Duration = 6000, VaryByParam = "none")]
        public ActionResult Cached()
        {
            // You could return whatever you want here, even a view
            // but for the purpose of the demonstration I am simply
            // returning a dynamic string value
            return Content(DateTime.Now.ToLongTimeString(), "text/html");
        }
    }
    

    and inside the Index.cshtml and About.cshtml views you could include the child action:

    <div>
        @{Html.RenderAction("Cached");}
    </div>
    

    and it you will get the cached version of it in both pages.