What is caching in Asp.net MVC?

Posted by  Pedro Araez
 282  View(s)
Rate this:

Please describe to me about caching in MVC and why we used it with an example.

  1. Re: What is caching in Asp.net MVC?

    The most common ASP.NET techniques are Caching which is used to improve the performance of the application. Here, Caching means to store something in memory which is being used frequently to provide better performance and in ASP.NET MVC, there is an OutputCache filter attribute which we can apply and it is the same concept as output caching in web forms. The output cache enables us to cache the content returned by a controller action.

    Output caching allows us to store the output of a particular controller in the memory. So any future request coming for the same action in which controller will be returned from the cached result. In this way, the same content does not need to be generated each and every time the same controller action is invoked.

    Why Caching?

    Caching is needed in many different scenarios to improve the performance of an application. For example, we have an ASP.NET MVC application, which displays a list of employees. Whenever these records are retrieved from the database by executing a database query each and every time a user invokes the controller action it returns the Index view.

    Therefore, we can take advantage of the output cache to avoid executing a database query every time we invoke the same controller action and in this case, the view will be retrieved from the cache memory instead of being regenerated from the controller action.

    Caching enables us to avoid performing redundant work on the server.

    Look at a simple example of caching in the project.

    [OutputCache(Duration = 60)]
    public ActionResult Index(){
       var employees = from e in db.Employees
       orderby e.ID
       select e;
       return View(employees);

    We can see that we have added the “OutputCache” attribute on the index action of the EmployeeController.

    What is caching in Asp.net MVC?

    Now, refresh the browser again within 60 seconds and we will see that the breakpoint is not hit this time and because we have used output cache with duration of seconds and it will cache this result for 60 seconds and when we refresh the browser then it will get the result from the cache, and it won’t load the content from the database server.

    There are other settings options as well which we can use with output cache. All these settings are not only for MVC framework but it is inherited from ASP.Net Caching.