缓存MVC剃刀中的保管箱项目.怎么做?

ami*_*tel 3 outputcache asp.net-mvc-3

如何在MVC中为下拉列表缓存我的项目和值?

有办法吗?

我在控制器中这样做.

示例代码是.......

    public ActionResult Index()
    {
        RegionTasks regionTasks = new RegionTasks();
        ViewBag.Region = GetRegions();}
Run Code Online (Sandbox Code Playgroud)

我的控制器具有如下功能.

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

我已经测试过它并没有缓存该区域的项目.

我怎样才能做到这一点?

Dar*_*rov 8

OutputCache属性用于控制器操作以缓存结果输出.它对其他方法没有任何影响.

如果要缓存自定义对象,可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

regionTasks现在下缓存regions键,然后从任何地方有权访问的ASP.NET应用程序访问HttpContext.Cache.