OutputCache Attribute in MVC

OutputCache Attribute in ASP.NET MVC

In this article, I am going to discuss the OutputCache Attribute in MVC application with examples. Please read our previous article before proceeding to this article where we discussed how to use the Child Action Only Attribute in MVC application. The OutputCache Attribute belongs to Results Filter category.

Why we need OutputCache Attribute in ASP.NET MVC?

In order to implement Caching, we need the OutputCache Attribute in MVC. The OutputCache Attribute in MVC is used to cache the content returned by a controller action method for a specific time period, so that, if a request comes within that time period, then the content is going to return from the cache memory.

So, with the help of caching, we can drastically improve the performance of an ASP.NET MVC Application. This filter can also be applied on Action Method or on the controller.

The OutputCache Attribute has several properties like CacheProfile, Duration, Location, VaryByParam, VaryByHeader, NoStore, etc. We will discuss the use of each property.

Why Caching?

As we already discussed to improve the performance of an application we need caching. For example, if we have an ASP.NET MVC application, which displays list employees or list of cities or list of countries. Now if we want to retrieve all the above master data from a database, then we need to execute the database query each and every time the user invokes the controller action method and then return the view.

In such scenarios, we can take advantage of the OutputCache Attribute to avoid executing the action method each and every time whenever the user wants to retrieve the view. Here, the view is going to be returned from the cache memory instead of being regenerated by the controller action method.

Let us understand this with an example. 

SQL Script for this demo
-- Create a Employee Table
Create table Employee
(
  ID int identity primary key,
  Name nvarchar(50),
  Gender nvarchar(10),
  Email nvarchar(50),
  Salary decimal(18,2)
)

-- Insert some test data for testing purpose
Insert into Employee values('Pranaya Rout', 'Male', 'Pranaya.Rout@test.com', 3000)
Insert into Employee values('Mitali Rout', 'Female', 'Mitali.Rout@test.com', 4000)
Insert into Employee values('Sara Nani', 'Female', 'Sara.Nani@test.com', 1000)
Insert into Employee values('James Histo', 'Male', 'James.Histo@test.com', 2000)
Insert into Employee values('Mary Jane', 'Female', 'Mary.Jane@test.com', 3000)
Insert into Employee values('Paul Sensit', 'Male', 'Paul.Sensit@test.com', 4000)

Select * from Employee

OutputCache Attribute in MVC

Create a new MVC application:

Open Visual Studio and create a new project. Select File => New => Project as shown below.

OutputCache Attribute in ASP.NET MVC

After clicking on “Project” link a new dialog will pop up. In that we are going to select web templates from the left pane after selecting web template, we need to select “ASP.NET Web Application” as shown below.

MVC OutputCache Attribute

After selecting this project template next we are going to name the project as “CachinginMVC” and clicking on the OK button a new dialog will pop up with Name “New ASP.NET Project” for selecting project Templates.

ASP.NET MVC OutputCache Attribute

In this dialog, we are going to choose MVC project template and then we are going to choose Authentication type for doing that just click on Change Authentication button, a new dialog will pop up with the nameChange Authenticationhere we are going to choose No Authentication click on OK Button.

It will take some time to create a project for us. Next, add a folder called DAL to our project.

Right Click on the Project => Add => New Folder

Rename the folder name as DAL

Adding ADO.NET Data Model inside DAL Folder

Right click on DAL folder then Add => New Item. Select ADO.NET data Model, Provide a meaningful name “EmployeeDataModel” and click on the ADD button as shown below

ASP.NET MVC OutputCache Filter

In the next step From Choose Entity data Model Screen choose Generate From Database and Click Next as shown below

OutputCache Attribute

From the next screen Click on New Connection and provide the necessary details, Select the database and click on OK as shown below

OutputCache Attribute in MVC

In the next step provide a meaningful name “EmployeeDBContext” for the Connection String that is going to create in Web.config file and click on Next as shown below

OutputCache Attribute in MVC

In the next step From Choose your database objects screen, choose the Employee object, provide the namespace name and click on Finish button as shown below

OutputCache Attribute in MVC

Following is the auto-generated EMPLOYEE model generated by Entity Framework

namespace CachinginMVC.DAL
{
    using System;
    using System.Collections.Generic;
    
    public partial class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Email { get; set; }
        public Nullable<decimal> Salary { get; set; }
    }
}
Adding EmployeeController.

Right click on Controllers Folder and select Add => Controller. Then select MVC5 Controller with Views, using Entity Framework

OutputCache Attribute in MVC

Once we click on Add button one popup will open. Provide the following details

  1. Model Class: Employee (CachinginMVC.DAL)
  2. Data Context Class: EmployeeDBContext (CachinginMVC.DAL)
  3. Controller Name: EmployeesController
  4. Rest is as it is and click on the Add button as shown below

OutputCache Attribute in MVC

Modify the Index() action method in EmployeesController as shown below. Notice that, we are using OutPutCache attribute to cache the content returned by Index() action method for 10 seconds. The Duration property of OutputCache attribute takes the value in seconds and then cache the result in the memory for that many seconds.

[OutputCache(Duration = 10)]
public ActionResult Index()
{
    System.Threading.Thread.Sleep(3000);
    return View(db.Employees.ToList());
}
Modify code in “Index.cshtml” view as shown below.
@model IEnumerable<CachinginMVC.DAL.Employee>

@{
    ViewBag.Title = "Index";
}

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<p>
    <b>Employee List retrieved @@ @DateTime.Now.ToString()</b>
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Gender)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Email)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Salary)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Gender)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Email)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })
            </td>
        </tr>
    }
</table>
Changes to RouteConfig.cs file
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Employees", action = "Index", id = UrlParameter.Optional }
        );
    }
}

When we navigate to /Employees/Index, the view output is cached for 10 seconds. If we refresh the view, within 10 seconds, then we will get the cached response of that view. After 10 seconds, the cache expires, the code is executed again and the output is cached for another 10 seconds.

Caching specific portion of a view using ChildActionOnly attribute:

Step 1: Remove OutputCache attribute and the line which calls Thread.Sleep(), from the Index() action method in EmployeeController. After the changes, the Index() action method should be as shown below.

public ActionResult Index()
{
    return View(db.Employees.ToList());
}

Add GetEmployeeCount() action method to EmployeeController. Notice that, this method is decorated with OutputCache and ChildActionOnly attributes. 

Child actions can be used to implement partial caching, although not necessary. In this case, even if the ChildActionOnly attribute is removed, a portion of the view will be cached as expected

[ChildActionOnly]
[OutputCache(Duration = 10)]
public string GetEmployeeCount()
{
    return "Employee Count = " + db.Employees.Count().ToString() + "@ " + DateTime.Now.ToString();
}

Copy and paste the following code, just below the closing table tag in Index.cshtml view.

<br /><br />
<b> @Html.Action(“GetEmployeeCount”) </b>

Navigate to /Employee/Index. Notice that, every time we refresh the page, the time in the section of the page that displays employee list changes, but not the time, that displays the employee count. This proves that only a portion of the view is cached. 

In the next article, I am going to discuss the different Properties of OutputCache Attribute in MVC

SUMMARY

In this article, I try to explain the OutputCache Attribute in ASP.NET MVC application step by step with a simple example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article. 

Leave a Reply

Your email address will not be published. Required fields are marked *