ASP.NET MVC > Caching

Cache partial view output in ASP.NET MVC

How to cache the partial view output?


To cache a partial view output, we again use the same OutputCache attribute to the action method that returns partial view result. To demonstrate this, lets create a example.

First create an action method

CONTROLLER METHOD

Code - 1

public ActionResult PartialViewCache()
  {
      return View();
  }

VIEW OF THE ABOVE ACTION METHOD

Code - 2

@{
    ViewBag.Title = "Partial View Cache";
}

<h2>Partial View Cache</h2>

@{
    Html.RenderAction("PartialViewCacheChild");
}

<h2>This date and time is coming from Parent View</h2>
<p>@DateTime.Now.ToString("T")</p>

CONTROLLER METHOD

Code - 3

[ChildActionOnly]
[OutputCache(Duration = 10)]
public PartialViewResult PartialViewCacheChild()
{
    return PartialView("_PartialViewForCache");
}

The above method is a child action method only because of [ChildActionOnly] attribute, it means this method can’t be called directly from the url like any other action method. It can only be called from within a View with the help of @Html.RenderAction or @Html.Action

Now create a partial view (follow the steps described in how to create a partial view).

_PARTIALVIEWFORCACHE.CSHTML VIEW

Code - 4

<h2>This date and time is coming from Partial View</h2>
<p>@DateTime.Now.ToString("T")</p>

Above view simply returns a statement and current date time.

Now when the first Action method (Code -1, PartialViewCache) is called, the PartialViewCache view renders (Code - 2) that internally calls PartialViewCacheChild method (Code - 3) using Html.RenderAction method that returns _PartialViewForCache partial view (Code - 4). 

Notice that in both view and partial view, current time is being retuned. Notice the definition of the PartialViewCacheChild method that is decorated with OutputCache with duration as 10; ie. its output will be cached for 10 seconds.

First request output of the View

Next request within 10 seconds give the same output from the partial view however the current date time of the View changes

 Views: 34632 | Post Order: 98



Write for us






Hosting Recommendations