This is one of the action filter that can be applied to controller action methods or entire controller for a specified amount of time.
Let us see the example of cache the output of view for 1 minute.After that it will display new time.
Step 1: Go to Solution explorer,Right click Controller and add controller
Step 2: Select MVC 5 Controller - Empty
Step 3: Give the controller name as 'SampleController'
Step 4:
Now I am going to display current time.Here i have given delay time as 60 seconds.So upto 1 minute or 60 seconds it will display
the old time.After 1 minute the current time label will update.
Code Snippet:
public class SampleController : Controller
{
// GET: Sample
[OutputCache(Duration =60)]
public ActionResult Index()
{
return View();
}
}
Step 5: Now add view for the samplecontroller.
Step 6: Write the following code in view, to display the current time
public class SampleController : Controller
{
// GET: Sample
[OutputCache(Duration =60)]
public ActionResult Index()
{
ViewBag.displaytime = DateTime.Now.ToShortTimeString();
return View();
}
}
VIEW:
<h2>CURRENT DISPLAY TIME: @ViewBag.displaytime<h2>
Step 7: Check the output now.
How to cache the content when the users are in different location?
By default where content is cached?
When [outputcache] attribute is used, the content is cached in three locations,
You can control where the control to be cached,by modifying the location property on outputcache attribute
Most of the time you might want to cache only on server or sometimes only on browser.
If you are displaying information about each user then you should not cache information on the server.if you are displaying different information to different users then you should cache information related to client.,
For example, if 2 persons login to my usmtechworld from different location let us say one from India and another from Japan.Actually you didnt give anything in location property of output cache.so by default it will take as any.When indian user enters , he will see 'Hi India' .If Japan user enters into my site he will also
see 'hi India'.This is because the content is cached in webserver.This is due to the fact that the indian user enters into the website first.
[OutputCache(Duration =60,Location =System.Web.UI.OutputCacheLocation.Client)]
The above code will cache the user based on their location and not based on webservers location.Now it will display the details based
on client location.(i.e Indian User logs in to the system will see "Hi India" and Japan user after logs in to the system will see "Hi Japan".)