OutputCache Attribute in MVC

OutputCache Attribute in ASP.NET MVC

In this article, I am going to discuss the OutputCache Attribute in the ASP.NET 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 the ASP.NET MVC application. The OutputCache attribute belongs to the Results Filter category.

Why do we need OutputCache Attribute in ASP.NET MVC?

In order to implement Caching in ASP.NET MVC Application, we need the OutputCache Attribute. The OutputCache Attribute in ASP.NET MVC Application is used to cache the content returned by a controller action method for a specific time period, so that, if the subsequent request comes within that time period, then the content is going to be returned 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 to the 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 the list of states or a list of cities or a list of countries, etc, like some master that which does not change that frequently. 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 in ASP.NET MVC 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.

Example: OutputCache Attribute in ASP.NET MVC

Let us understand OutputCache Attribute in ASP.NET MVC Application with an example. We are going to use the following Employee table in this example.

OutputCache Attribute in ASP.NET MVC

Please use the below SQL script to create and populate the Employee table with the required sample data.

-- 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)
Create a new MVC application:

Create a new ASP.NET MVC Project. Once you create the ASP.NET MVC 5 Application, then create a new folder by Right-Clicking on the Project and select Add => New Folder and Rename the folder name as DAL

Adding ADO.NET Data Model inside DAL Folder

Now add ADO.NET Entity Data Model and follow the Database First Approach and create the EDMX file for our Employee table. Once you create the EDMX file, then the 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 the Controllers folder and then select Add => Controller. Then select MVC5 Controller with views, using Entity Framework as shown in the below image.

ASP.NET MVC OutputCache Attribute

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 in the below image.

MVC OutputCache Attribute

Modify the Index() action method in EmployeesController as shown below. Notice that, we are using the OutPutCache attribute to cache the content returned by the Index() action method for 10 seconds. The Duration property of the OutputCache attribute takes the value in seconds and then caches 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 the “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:

Step1: 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 the 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 the ASP.NET MVC Application. Here, in this article, I try to explain the OutputCache Attribute in ASP.NET MVC application with Examples. I hope this OutputCache Attribute in the MVC article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this OutputCache Attribute in the MVC article. 

1 thought on “OutputCache Attribute in MVC”

Leave a Reply

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