Lets Have a fun with Technology.

BTemplates.com

Follow by Email

Wednesday, March 23, 2016

Implement Caching in MVC Application.


Hello,

Caching is important in all web application.

MVC Provide better way to do this. 

Lets create simple caching application in MVC. This application store Datetime in Cache.


First create sample application as shown in below article.


http://dotnet-magic.blogspot.in/2016/03/how-to-create-simple-mvc-application.html


Now add below code in controller. It will return current system datetime.




      public ActionResult Index()

        {

            return Content(DateTime.Now.ToString());

        }

Now run your application. it will display current date time. Each time if you refresh your web page it will display current date time of system.





Now Lets implement caching in this application.

Change your code as shown below




[OutputCache(Duration = 300, VaryByParam = "none")]
public ActionResult Index()
        {
            return Content(DateTime.Now.ToString());
        }

Now run your application. it will show current system date time . After some time (Before 5 min. Duration is 5 minute) again refresh it. it will still show old time. This is magic of Caching.

Now look at above declaration. You will find VaryByParam property.
What;s a significant of this property. Well We may store whole master in cache. For example Country master, state master etc.. Now suppose we see details of one country then this property will helpful. in VaryByParam we will provide countryid as parameter. so it will filter from countryID.





[OutputCache(Duration = 300, VaryByParam = "countryID")]
public ActionResult GetCountryDetail(int contryID)
        { 
            Country c = new Country()
            return Content(c.getCountryDetails(countryID));
        }

Now you have question where this cache data is stored. However we have property to specify this. You can store data either on client machine or server machine or proxy server.

"Location" is property for this. Below is different value for this property.




For different option description look at blow article.

https://msdn.microsoft.com/en-in/library/system.web.ui.outputcachelocation(v=vs.110).aspx

Lets me know if you have question in this simple implementation.

0 comments:

Post a Comment