ASP.NET MVC > Caching

Store data into Cache in ASP.NET MVC in ASP.NET MVC

How to store data into Cache in ASP.NET MVC?


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 METHOD

public ActionResult CacheOutput()
{
    if (HttpContext.Cache["MyDate"] == null)
    {
        HttpContext.Cache["MyDate"] = DateTime.Now;
    }

    ViewBag.DateTime = HttpContext.Cache["MyDate"];

    return View();
}

Above action method first checks for the null value in HttpContext.Cache[“MyDate”] and it its null then saves current date in the Cache. Next line simply keep the data from the Cache into ViewBag.DateTime.

VIEW

@{
    ViewBag.Title = "Cache Output";
}

<h2>Cache Output</h2>

Cached time is : @ViewBag.DateTime

The same ViewBag.DateTime is being retrieved in the above view and the output looks like below.

 Views: 23272 | Post Order: 99



Write for us






Hosting Recommendations