Search:
Welcome Guest | Register | Login
logo

How to cache data in MVC for 1 hours or 1 month?

In our application we are using drop down to select a product from the list of products. We kept all the products in database and search from there.

A product can be added might be in months, so I want to cache my data for atleast one hour or one month, is there any quick and effective way to do this?

Here is my repository and controller code to get data from database

// Repository Code 
public static List<Product> Product_Fetch()
{
    MyDataContext db = new  MyDataContext ();
    db.Products.Where(x=>x.IsActive == true).ToList<Product>();        
}

// Controller Code
public ActionResult ProductFetch()
{    
     return view(ProductRepository.Product_Fetch())
}    
  • MVC
  • Caching
2
 
Asked: 02 Mar 2013
Reputation: 52
Nikita Bhavsar
2 Answers

In MVC to cache data is easy just add attribute [OutputCache(Duration = timeinsecond)] and your data will be cached, so your controller code will be

For one hour: 60 Second x 60 minute = 3600

[OutputCache(Duration = 3600)]
public ActionResult ProductFetch()
{    
   return view(ProductRepository.Product_Fetch())
}  

For one month: 60 sec x 60 min x 24 hours x 30 days = 2592000

[OutputCache(Duration = 2592000)]
public ActionResult ProductFetch()
{    
   return view(ProductRepository.Product_Fetch())
} 
2
 
Answered: 02 Mar 2013
Reputation: 2,075
Hamden

Logic: check if data is in cache then read from there otherwise read from database and cache it.

[OutputCache(Duration = 3600)]
public ActionResult ProductFetch()
{
    if (System.Web.HttpContext.Current.Cache["Products"] != null)
      return View((List<Product>)System.Web.HttpContext.Current.Cache["Products"]);
    else
    {
      List<Product> products= ProductRepository.Product_Fetch();
      System.Web.HttpContext.Current.Cache["Products"] = products;
      return View(products);
    }
}    
0
 
Answered: 02 Mar 2013
Reputation: 1,304
Myghty
Login to post your answer