Cache Caching Elements in Razor MVC. How to do it?

How can I cache my items and values ​​for a dropdown in MVC?

Is there a way to do this?

I am doing this in a controller.

Example code: .......

    public ActionResult Index()
    {
        RegionTasks regionTasks = new RegionTasks();
        ViewBag.Region = GetRegions();}

      

My controller has a function like below.

 [OutputCache(Duration = 10, Location = System.Web.UI.OutputCacheLocation.Server)]
    private IEnumerable<SelectListItem> GetRegions()
    {
        RegionTasks regionTasks = new RegionTasks();
       return regionTasks.GetRegions();
    }

      

I have tested and not cached item for scope.

How can i do this?

+3


source to share


2 answers


Darin is also right, however, I made the following code to store it on the server for X minutes.



 private IEnumerable<SelectListItem> GetGlobalUrlRegion(string profileName)
    {
        string cacheKey = "cacheUrlRegion";
        RegionTasks regionTasks = RegionTasks.CreateRegionTasks();
        IEnumerable<SelectListItem> regionUrlList = HttpContext.Cache[cacheKey] as IEnumerable<SelectListItem>;
        if (regionUrlList == null)
        {
            var regionObject = regionTasks.GetRegions(profileName);
            var cTime = DateTime.Now.AddMinutes(int.Parse(System.Configuration.ConfigurationSettings.AppSettings["GlobalCacheDurationInMin"].ToString()));
            var cExp = System.Web.Caching.Cache.NoSlidingExpiration;
            var cPri = System.Web.Caching.CacheItemPriority.Normal;
            regionUrlList = regionObject;
            HttpContext.Cache.Insert(cacheKey, regionObject, null, cTime, cExp, cPri, null);
        }

        return regionUrlList;
    }

      

+2


source


The attribute is OutputCache

used for controller actions to cache the received result. This does not affect other methods.

If you want to cache custom objects, you can use HttpContext.Cache

:



private IEnumerable<SelectListItem> GetRegions()
{
    var regionTasks = HttpContext.Cache["regions"] as IEnumerable<SelectListItem>;
    if (regionTasks == null)
    {
        // nothing in the cache => we perform some expensive query to
        // fetch the result
        regionTasks = new RegionTasks().GetRegions();

        // and we cache it so that the next time we don't need to perform
        // the query
        HttpContext.Cache["regions"] = regionTasks;
    }

    return regionTasks;
}

      

regionTasks

are now keyed cached regions

and accessible from anywhere in your ASP.NET application that has access to HttpContext.Cache

.

+8


source







All Articles