Updated on Kisan Patel
Storing data into Cache in ASP.NET MVC is not as straightforward as it was in ASP.NET Web Form where we used to use Cache[“key”] and value.
Here, we will need to use HttpContext.Cache object and remaining approach are same.
Controller Code :
public ActionResult CacheOutput() { if (HttpContext.Cache["CurrentDate"] == null) { HttpContext.Cache["CurrentDate"] = DateTime.Now; } ViewBag.DateTime = HttpContext.Cache["CurrentDate"]; return View(); }
» In this action method it first checks for the null value in HttpContext.Cache["CurrentDate"]
and it its null then saves current date in the Cache.
» Next line simply keep the data from the Cache into ViewBag.DateTime
. so now you can get your ciewBag in view and pring that datetime in it.
View As :
Cached time is : @ViewBag.DateTime