如何缓存mvc3 webgrid结果(以便col排序点击不?

时间:2011-09-24 16:27:42

标签: asp.net-mvc-3 webgrid

有人可以告诉我如何缓存我的webgrid结果,这样当我按列排序时,它不会每次都重新运行我的存储过程查询吗?

当单击列链接进行排序时,每次重新执行填充表/网格的存储过程(有点慢)并命中数据库。任何缓存提示和技巧将不胜感激。

THX!

1 个答案:

答案 0 :(得分:2)

在控制器操作内部,调用存储库中的方法应该查询数据库,您可以检查缓存是否已包含结果。

这是一种常用的模式:

public ActionResult Foo()
{
    // Try fetching the results from the cache
    var results = HttpContext.Cache["results"] as IEnumerable<MyViewModel>;
    if (results == null)
    {
        // the results were not found in the cache => invoke the expensive 
        // operation to fetch them
        results = _repository.GetResults();

        // store the results into the cache so that on subsequent calls on this action
        // the expensive operation would not be called
        HttpContext.Cache["results"] = results;
    }

    // return the results to the view for displaying
    return View(results);
}