Introduction
One of the best ways to improve the performance of an ASP.NET MVC application is by caching. With the help of caching, we can reduce the database server round trips. We can apply OutputCache Action Filter either on Action Method or on the controller. The OutputCache attribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked.
OutputCache attribute has several properties.
- CacheProfile
- Duration
- Location
- VaryByParam
- VaryByHeader
- NoStore
Why do we need Caching?
We need caching in many different scenarios to improve the performance of an application. For example, if we have an ASP.NET MVC application, which displays a list of employees. Now, when these records are retrieved from the database by executing a database query, each and every time a user invokes the controller action, it returns the Index view.
We can take advantage of the output cache to avoid executing a database query every time a user invokes the same controller action. In this case, the view will be retrieved from the cache instead of being regenerated from the controller action.
Step 1
Open Visual Studio 2015 or your choice and create a new project.
Step 2
Choose the web application project and give an appropriate name to your project.
Step 3
Select the empty template, check on MVC checkbox below, and click OK.
Step 4
Right-click on the Models folder and add a database model. Add Entity Framework now. For that, right-click on Models folder, select Add, then select New Item.
You will get a window; from there, select Data from the left panel and choose ADO.NET Entity Data Model, give it the name EmployeeModel (this name is not mandatory, you can give any name) and click "Add".
After you click on "Add a window", the wizard will open. Choose EF Designer from the database and click "Next".
After clicking on "Next", a window will appear. Choose "New Connection". Another window will appear. Add your server name - if it is local, then enter a dot (.). Choose your database and click "OK".
The connection will be added. If you wish, save the connection name as you want. You can change the name of your connection below. It will save the connection in the web config. Now, click "Next",
After clicking on NEXT, another window will appear. Choose the database table name as shown in the below screenshot and click "Finish".
Entity Framework gets added and the respective class gets generated under the Models folder.
Step 5
Right click on controllers folder add controller.
A window will appear. Choose MVC5 Controller-Empty and click "Add".
After clicking on "Add", another window will appear with DefaultController. Change the name to HomeController and click "Add". The HomeController will be added under the Controllers folder. Don’t change the Controller suffix for all controllers, change only the highlight, and instead of Default, just change Home;
Complete code for Home Controller
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Web;
- using System.Web.Mvc;
- using MvcFilters_Demo.Models;
-
- namespace MvcFilters_Demo.Controllers
- {
- public class HomeController : Controller
- {
- private readonly EmployeeContext _dbContext =new EmployeeContext();
-
-
- [OutputCache(CacheProfile = "1MinutCatche")]
- public ActionResult Index()
- {
- System.Threading.Thread.Sleep(3000);
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
- public ActionResult Details(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var employee = _dbContext.Employees.Find(id);
- if (employee==null)
- {
- return HttpNotFound();
- }
-
- return View(employee);
- }
- }
- }
Step 6
Right click on Index method in HomeController The "Add View" window will appear with default index name checked (use a Layout page), and click on "Add.
- @using System.Globalization
- @model IEnumerable<MvcFilters_Demo.Models.Employee>
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>List of Employee</h2>
- <b>Employee List retrieved @@ @DateTime.Now.ToString(CultureInfo.CurrentCulture)</b>
-
- <table class="table table-bordered">
- <thead>
- <tr>
- <th>@Html.DisplayNameFor(m=>m.Name)</th>
- <th>@Html.DisplayNameFor(m=>m.Gender)</th>
- <th>@Html.DisplayNameFor(m=>m.Age)</th>
- <th>@Html.DisplayNameFor(m=>m.Position)</th>
- <th>@Html.DisplayNameFor(m=>m.Office)</th>
- <th>@Html.DisplayNameFor(m=>m.HireDate)</th>
- <th>@Html.DisplayNameFor(m=>m.Salary)</th>
- <th>Action(s)</th>
- </tr>
- </thead>
- <tbody>
- @foreach (var emp in Model)
- {
- <tr>
- <td>@emp.Name</td>
- <td>@emp.Gender</td>
- <td>@emp.Age</td>
- <td>@emp.Position</td>
- <td>@emp.Office</td>
- <td>@emp.HireDate</td>
- <td>@emp.Salary</td>
- <td>@Html.ActionLink("Details","Details",new {id=emp.EmployeeId})</td>
- </tr>
- }
- </tbody>
- </table>
Step 7
Right click on Details method in HomeController. The "Add View" window will appear with default Details name checked (use a Layout page), and click on "Add.
Code for details view
- @model MvcFilters_Demo.Models.Employee
- @{
- ViewBag.Title = "Details";
- }
-
- <h2>Employee Details</h2>
- <dl class="dl-horizontal">
- <dt>@Html.DisplayNameFor(m => m.Name)</dt>
- <dd>@Html.DisplayFor(m => m.Name)</dd>
- <dt>@Html.DisplayNameFor(m => m.Gender)</dt>
- <dd>@Html.DisplayFor(m => m.Gender)</dd>
- <dt>@Html.DisplayNameFor(m => m.Age)</dt>
- <dd>@Html.DisplayFor(m => m.Age)</dd>
- <dt>@Html.DisplayNameFor(m => m.Position)</dt>
- <dd>@Html.DisplayFor(m => m.Position)</dd>
- <dt>@Html.DisplayNameFor(m => m.Office)</dt>
- <dd>@Html.DisplayFor(m => m.Office)</dd>
- <dt>@Html.DisplayNameFor(m => m.HireDate)</dt>
- <dd>@Html.DisplayFor(m => m.HireDate)</dd>
- <dt>@Html.DisplayNameFor(m => m.Salary)</dt>
- <dd>@Html.DisplayFor(m => m.Salary)</dd>
- </dl>
OutputCache
- [OutputCache(Duration = 15)]
- public ActionResult Index()
- {
- System.Threading.Thread.Sleep(3000);
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
OutputCache with Location property
- [OutputCache(Duration = 15, VaryByParam ="none",Location = System.Web.UI.OutputCacheLocation.Client)]
- public ActionResult Index()
- {
- System.Threading.Thread.Sleep(3000);
- var employee = _dbContext.Employees.ToList();
- return View(employee);
- }
-
- [OutputCache(Duration = int.MaxValue, VaryByParam = "id")]
- public ActionResult Details(int? id)
- {
- if (id == null)
- {
- return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
- }
- var employee = _dbContext.Employees.Find(id);
- if (employee==null)
- {
- return HttpNotFound();
- }
-
- return View(employee);
- }
CacheProfiles
- <caching>
- <outputCacheSettings>
- <outputCacheProfiles>
- <clear/>
- <add name="1MinutCatche" duration="60" varyByParam="none"/>
- </outputCacheProfiles>
- </outputCacheSettings>
- </caching>
-
- [OutputCache(CacheProfile = "1MinutCatche")]
- public ActionResult Index()
- {
- System.Threading.Thread.Sleep(3000);
- var employee = _dbContext.Employees.ToList();
- return View(employee);
Step 8
Built and run your project by ctrl and F5.