M a r k W o r r a l l . c o m
all articles / all Coding articles

How To Cache Data in Application State for ASP.NET MVC

C# ASP.NET MVC Visual Studio 2015

If you find your application loading the same data many times over, data that doesn't change very often, then it should probably be cached. A common example of this are lists of lookup values, I refer to them as static lookups, as their values rarely change.

There are differnt types of caching. If the same lists are used by all users of an ASP.NET web application, then they could be stored in Application state so there is only one copy of them held in memory on the server, and all users share the same copy.

Here is a simple process to cache data in Application state for ASP.Net MVC web applications.


1. Create a new Visual Studio 2015 project


2. Select 'ASP.Net Web Application'

Application Cache Demo 1

3. Change the name to 'ApplicationCacheDemo' and press OK


4. Select 'MVC' and Change Authentication to 'No Authentication' and press OK to create the project

Application Cache Demo 2

5. In the root directory create a new class called 'Location', this is the collection of objects that will cached. Add the following properties to the Location class:


namespace ApplicationCacheDemo
{
    public class Location
    {
        public int Id;
        public string Name;
    }
}


6. In the Models directory create a new class called 'Home_Index_Model'. I always create a model per page to hold whatever data that page will need, or return, and name it to reflect its location. Add the following properties to the Location class:


using System.Collections.Generic;
using System.Web.Mvc;
namespace ApplicationCacheDemo.Models
{
    public class Home_Index_Model
    {
        //collection of objects
        public IEnumerable Locations { get; set; }
    }
}


7. Create a new folder in the root directory called 'Common'


8. In Common, create a new class called ApplicationCache. Note it is static as it will be shared by all users. Replace the code with the following code:


using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ApplicationCacheDemo.Common
{
    public static class ApplicationCache
    {
        public static HttpContext httpContext { get; set; }

        //get a fresh list of Location objects from the Database
        public static void CacheLocations()
        {
            var location = new Location();
            IList locations = new List();
            foreach (var item in GetLocationsFromDB().OrderBy(x => x.Name).ToList())
            {
                locations.Add(item);
            }
            httpContext.Application["Locations"] = locations;
        }

        //return a list of cached Location objects
        public static IList Locations
        {
            get
            {
                object obj = httpContext.Application["Locations"];
                if (obj == null)
                {
                    CacheLocations();
                    obj = httpContext.Application["Locations"];
                }
                return (IList)obj;
            }
        }
        
        //Clear Locations from the Application cache
        public static void LocationsClear()
        {
            httpContext.Application["Locations"] = null;
        }

        //replace with code to retrieve list from Database
        private static IList GetLocations()
        {
            var locations = new List() {
                                new Location()
                                {
                                    Id = 1,
                                    Name = "Wolverhampton"
                                },
                                new Location()
                                {
                                    Id = 2,
                                    Name = "Brisbane"
                                },
                                new Location()
                                {
                                    Id = 3,
                                    Name = "Reading"
                                },
                                new Location()
                                {
                                    Id = 4,
                                    Name = "Dartmoor"
                                }
            };
            return locations;
        }
    }
}

This has 3 main methods:

Locations - retrieves the contents of "Locations" (collection of Location objects) from Application state and checks if it populated. If it is, it returns the collection. If not, it calls CacheLocations() to load them.

CacheLocations() - retrieves the collection of Location objects from wherever they are persisted. This would normally be from a database, but for simplicity in this example it calls local procedure GetLocations() which just returns a hard coded list.

LocationsClear() - clears Application state for Locations, so the next request for the collection will cause the data to be freshly loaded. If the data should ever be changed, we would call this to trigger its reloading a fresh set.


9. In the HomeController replace the code for Index() with the following code:


[HttpGet]
public ActionResult Index()
{
    var model = new Home_Index_Model();

    ApplicationCache.httpContext = System.Web.HttpContext.Current;
    model.Locations = ApplicationCache.Locations.ToList();

    return View(model);
}


10. In Views -> Home replace the markup in Index.cshtml with the following:


@model ApplicationCacheDemo.Models.Home_Index_Model

@{ 
        ViewBag.Title = "Home Page";
}

@foreach (var item in Model.Locations)
{
    @item.Id @item.Name
}


11. Press F5 to run the application. The view should iterate through and display the collection of Locations:

Application Cache Demo 3





Add Comment

*

*

*

capthca1 capthca2 capthca3 capthca4 capthca5 capthca6

*