How to cache mvc3 webgrid results (so that col sor

2020-03-30 06:33发布

问题:

Can somebody please tell me how I can cache my webgrid results so that when I sort by column it doesn't re-run my stored procedure query every time?

When clicking on a column link to sort, the stored proc (which is a little slow) that populates the table/grid is re-executed every time and hits the database. Any caching tips and tricks would be greatly appreciated.

Thx!

回答1:

Well inside the controller action which is invoking the method on your repository supposed to query the database you could check whether the cache already contains the results.

Here's a commonly used pattern:

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);
}