Caching in Asp.net MVC Example

Caching is one of the most powerful features in asp.net application development, here we learn about creating cache object and use object from cache.

Let’s understand caching in asp.net mvc, How to use Caching in Asp.net MVC to improve performance.

Caching Implementation: Caching is a technique which stores data in memory that is being used frequently, Caching is used to improve the performance in ASP.NET MVC Application

There are three type of caching in Asp.net

  • Output Caching
  • Data Caching
  • Fragment Caching

While learning caching in asp.net, we need to understand what type of data we should cache?
How that will help in application performance?
What are the dependencies of cached data? How to remove cache when required ?

Output Caching in Asp.net MVC with example

We can use caching in many different scenarios to improve the application performance.
For example, we have an ASP.NET MVC application for student management, which displays a list of students.

The application is being used by management team, they may need these records very often, and records are being retrieved from the database by executing a database query each and every time a user invokes the controller action that returns the “ManageStudents” view.

In this scenario, we can take advantage of output cache to avoid executing a database query every time, data can be retrieved from the cache instead of database.

Let's look at the code.

[OutputCache(Duration = 60)]
public ActionResult ManageStudents()
{
    ViewBag.DataTime = DateTime.Now.Millisecond;
    //ViewBag.Data = _dto.GetStudents();
    return View();
}

Now the page is cached for 60 seconds and within 60 seconds if there are multiple calls then instead of fetching from database it will fetch from cached object

VaryByParam in Caching: Now suppose you want to cache a page that shows data based on parameter, for example “viewStudent” view use parameter called “studentId” , that means the data will differ for each student
In this scenario use VaryByParam

[OutputCache(Duration = 120, VaryByParam = "StudentId", Location = OutputCacheLocation.Client)]
public ActionResult viewStudent()
{
    ViewBag.DataTime = DateTime.Now.Millisecond;
    //ViewBag.Data = _dto.GetStudent(StudentId);
    return View();
}

Note: in case your application showing user specific private data, ideally you should not cache it, because it should confirm that viewer is authorized to view the data.

Keep OutputCacheLocation in Client browser only where the request was originated from, keeping it on web server where it was processed may be good for content which are generic and often used by multiple user.

Data Caching in Asp.net MVC Example

Now we learn data caching in asp.net MVC with a real time example.

Just think you have a web application, where you need to display country list in many different places, in this situation instead of calling country list from database every time we call it from cache

let's look at the following code.

public ActionResult Index()
{ ViewBag.CountryList = GetCountryList();
return View();
}
List<Country> GetCountryList()
{
// every time we get a request, we will check the cache first
List< Country> _countryList = HttpContext.Cache.Get("countryList") as List< Country>;
         
    // if the cached object is null, then only fetch data from Database
    if (_countryList == null)
    {
    _countryList = CommonDTO.GetCountryList();
    //after fetching from database,insert the collection into Cache object.
    HttpContext.Cache.Insert("countryList", _countryList);
    }
return _countryList;
}

Remember Cache.Insert(key,value) will override the existing value, but Cache.Add(key,value) will throw exception if you try to add same key twice .

Fragment Caching in Asp.net MVC with example

Fragment caching means cache only particular portion of the web page to be cached. just like caching some partial view

Just think of situation where you have a side navigation menu, you create a partial view then call that partial view in every page.

So the navigation part is used very often, you can cache it on server for quick rendering

[ChildActionOnly]            
[OutputCache(Duration = 60)]
public PartialViewResult navigationMenu()
{
    return PartialView("_leftNavigation");
}

Take a look at how to create, implement, cache in partial view in mvc

Few advantages of Caching in Asp.net MVC Application
  • When content is cached at the client it reduce hosting server round-trips
  • When content is cached at the web server, it reduce database server round-trips
  • Since cached content reduce round-trips, it improve performance
  • Save time for regenerating reusable content

You also should read following posts about .Net Caching


 
Caching In ASP.NET MVC
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial