Tutorial for Donut Hole Caching - Partial View Caching in MVC


MVC3 has come up with a great concept of Partial page caching, also known as ‘Donut Hole Caching’ where entire donut represents your Main View and the donut hole represents partial view that you would like to cache.
Most of you might have faced the scenario of rendering HTML as a partial view. The HTML may be static or dynamic and say you are pulling it from third party or database. Now, each time going to database or third party is not feasible considering performance. So the option of caching comes into picture.
But, you may have some content on Main View you do not want to cache. So here is the approach to cache partial content of your main view.

Let me illustrate this with a simple example:

See above screenshot showing my MVC view. On high level, I have created one view i.e. ‘Index’ and a partial view i.e. ‘ChildView‘. ChildView has a content that need to be cached and it is rendered within Index view.

Basic steps of partial caching:
  1.   move content that need to be cached in a partial view
  2.  Create a child action in controller that will return partial view and attach OutputCache attribute to it.
  3. Write Content (that is going to be cached)  logic in child action
  4. Call this child action from Main View using Html.Action

In my sample example, I created a Main View a Label with current date time. Refer below image

ViewBag.Message in this view will contain Current Date time.Also note that I have added a call to my child action using  @Html.Action("ChildView").

Then I created a Child View also having a current date time as shown in below image.

ViewBag.Message in this view will contain Current Date time.
Note that you can use Html.Raw if you are returning Html content inside ViewBag.Message

Then I created two actions Index and ChildView for retuning Index View and Child View respectively.


 I have attached ChildActionOnly attribute so that action will be available only for internal calls. Also to cache Child View content, I have attached OutputCache attribute with 10 seconds duration.

Now when I will hit the Index view from browser, for the first time it will internally call ChildView Action and will display Current Date Time. But within 10 seconds, if I try to re-hit the Index view, then the Current Date Time in Index view will be updated for each hit (as I have not attached OutputCache attribute to Index action) and Current Date Time on Child View will be constant for 10 seconds.

First hit screenshot(Note:Parent and Child Date times are same)

 Second hit screenshot(Note:Parent and Child Date times are different and Child Date time is same as that of First hit Child Date time)



Post a Comment