Site icon Dotnet Helpers

Caching in MVC

Different types of Caching Part 1

Why caching needed?

Advantage of Caching

Remember while using Cache :

Output Cache Filter :

It’s used to cache the data that is output of an action method.In default, this will cache the data upto 60 seconds.After 60 seconds, Asp.Net MVC will execute the action method again and start caching the output again.

Let we see with example..

Controller :

public class OutputCachingController : Controller
{

[OutputCache(Duration = 20, VaryByParam = “none”)]
public ActionResult Index()
{
ViewBag.CurrentDateTime = DateTime.Now.ToString();
return View();
}
}

View :

@{  ViewBag.Title = “Index”;}
<h2>Index</h2>
<h1>@ViewBag.CurrentDateTime</h1>

Run the application, first time it will show the output like below

up to 20 seconds it will show the same time in the browser without changing after we refresh the page because it will not call the action method upto 20 seconds ( so no new time updated in the viewbag)

VaryByParam : This property enables you to create different cached versions of the content when a form parameter or query string parameter varies.

VaryByParam = “aadharsh”

If it find records matching “aadharsh” string then a cache will be created,if paremeter/querystring changes than it will replace the old one with new
content

Let we discuss about Donut caching and Donut Hole caching in Part 2

Exit mobile version