Introduction
MVC provides users a way to cache any output (view/data) from any controller for a definite time. This feature can also be used at action level. We will write a quick code to see this, in the following sections.
We will also create some cache profile and will be using them for caching different sections. This will make the caching strategy easy to cater to some extent of changes going further, without fresh deployment.
Let’s dive in to code now.
Let’s start with a blank MVC application
Open Visual Studio 2013 IDE, and create a new project as shown below:

Select ASP.NET Web Application:

Select Empty template and check MVC (so that MVC folders are created in code structure). Click on OK, no need to change any other option.

This will give us a blank MVC application where we can add the code required for this demo.
Add the code to see it happening
Let’s add a Home controller in the controller folder and add the following code in that:

Here we have three action methods:
- Index – This return index view.
- GetHeaderData – This return header data. For testing our cache code, we have also added date time there. This will tell us at what time this data has been fetched fromthe server. Ideally it should go to server to fetch the data only after the header cache is expired.
If you notice on the top of action method, we have added [OutputCache(Duration = 5)].
This tells the application to cache this data for 5 seconds and for any request for this data before cache is expired fetch the data from cache itself. Once cache is expired it should fetch the data again from the server.
- GetFooterData – This returns footer data. For testing our cache code, we have also added date time there. This will tell us at what time this data has been fetched from server. Ideally it should go to the server to fetch the data only after the footer cache is expired.
If you notice on the top of action method, we have added [OutputCache(Duration = 10)].
This tells the application to cache this data for 10 second and for any request for this data before cache is expired fetch the data from cache itself. Once cache is expired it should fetch the data again from the server.





SubashPosted Sep 15, 2016, 1:08 AM
Good one
Rajeev PunhaniPosted Feb 26, 2016, 1:50 AM
Nice.
Santhakumar MunuswamyPosted Feb 23, 2016, 2:16 PM
Thanks for nice article
Sibeesh VenuPosted Feb 23, 2016, 9:14 AM
Nice Share
Shubham KumarPosted Feb 23, 2016, 5:25 AM
Nice share
Rupali ShindePosted Feb 23, 2016, 5:06 AM
nice post
Vignesh ManiPosted Feb 22, 2016, 5:47 PM
Nice one
Ehsan SajjadPosted Feb 22, 2016, 1:57 PM
good one
Gowtham KPosted Feb 22, 2016, 11:54 AM
Nice Share
Suraj PantPosted Feb 22, 2016, 9:55 AM
Thanks Raja.
Raja TPosted Feb 22, 2016, 9:05 AM
Nice, Thanks for sharing