I am working on mvc4 web application. I want to cache some database queries results and views on server side. I used-
HttpRuntime.Cache.Insert()
but it caches the data on client side. Please help.
Store data into Cache in ASP.NET MVC in ASP.NET MVC Above action method first checks for the null value in HttpContext. Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag.
In ASP.NET MVC, there is an OutputCache filter attribute that you can apply and this is the same concept as output caching in web forms. The output cache enables you to cache the content returned by a controller action. Output caching basically allows you to store the output of a particular controller in the memory.
ASP.NET supports three types of caching: Page Output Caching [Output caching] Page Fragment Caching [Output caching] Data Caching.
The output cache enables you to cache the content returned by a controller action. That way, the same content does not need to be generated each and every time the same controller action is invoked. Imagine, for example, that your ASP.NET MVC application displays a list of database records in a view named Index.
I'm using MemoryCache to store query results, and it's working fine so far.
Here are a few links that I've used to implement it.
- Using MemoryCache in .NET 4.0 (codeproject)
- Using MemoryCache in .NET 4.0 (blog entry)
As I read them now, I find them not that clear, so maybe there is a better link that I've lost somewhere.
Here is a sample of my code which I hope is clear enough so that you see how it works
public static class AgencyCacheManager { private static MemoryCache _cache = MemoryCache.Default; public static List<RefAgency> ListAgency { get { if (!_cache.Contains("ListAgency")) RefreshListAgency(); return _cache.Get("ListAgency") as List<Agency>; } } public static void RefreshListAgency() { var listAgency = GetAllComplete(); CacheItemPolicy cacheItemPolicy = new CacheItemPolicy(); cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddDays(1); _cache.Add("ListAgency", listAgency, cacheItemPolicy); } }
And to retrieve the list from cache
public Agency FindBy(string agencyId) { return AgencyCacheManager.ListAgency.SingleOrDefault(x => x.AgencyPartnerCode == agencyId); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With