11

How can I cache the output of the PartialViews in ASp.NET MVC 3? I know I can decorate the action with [OutputCache] attribute but what I just want to include the @OutputCache right into the PartialView as shown below:

@OutputCacheAttribute

@model MvcApplication1.Models.someViewmodel

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>



@Html.Partial("_MyPartialView")
johndoe
  • 185
  • 1
  • 1
  • 6

1 Answers1

22

This cannot be done. You need to use the Html.Action helper to render a child action decorated with the [OutputCache] attribute and which will render the partial.

public class MyController : Controller
{
    [OutputCache(Duration = 3600)]
    public ActionResult Index()
    {
        return View();
    }
}

and then include the partial:

@model MvcApplication1.Models.someViewmodel
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@Html.Action("Index", "My")
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928