Saturday 7 March 2020

CACHE in Asp.Net MVC

CACHE in Asp.Net MVC

In this article you will learn how to use CACHE features in Asp.Net MVC.

What is CACHE ?
CACHE stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier request or computation or a copy of data stored.

By using CACHE after certain time system rebuild / re fetch data otherwise system will display the datas from CACHE only. Cache should be use on those method or process which called frequently.



Create an ASP.NET Web Application - Empty Template -- MVC  project called “AspNetMvcCache”  
















Followings things selected in given below dialog box :

1. Empty
2. MVC























Creating project . . 









Default view of SOLUTION EXPLORER


















Right click on Project, Now we are going to add LINQ to SQL Classes.













Specify the name of LINQ to SQL classes file.








Now switch to SERVER EXPLORER and click on Data Connections . . select Add Connection.. .













Fill the following dialog box as given below: 
Server Name : Your SQL server name or IP
Authentication and select database.






















After connection established successfully, now drag n drop tblMembers from Server Explorer to DBML (Linq to Sql class) canvas.

























Adding Controller:  Right click on CONTROLLERS folder and 
Select ADD--->Controller…

























Now you can see MemberController created, update following code in INDEX ActionMethod to get list of all Members.

// GET: Member
        public ActionResult Index()
        {
            //Create instance of LINQ To SQL class
            MemberDataClassesDataContext db = new MemberDataClassesDataContext();

            //Fetch Members records in list collection format
            var MemberList = (from a in db.tblMembers
                              select a).ToList();

            //returning MemberList to View
            return View(MemberList);
        }





After updating above code Right click on INDEX ActionMethod to create INDEX.CSHTML





















Now you can see INDEX.CSHTML created.
























At end of this article full source code given or you can download ZIP file.


Press < F5 > key to execute the project.


OUTPUT:















Now we are going to do CACHE related activities.

Switch to MemberController and mark  BREAKPOINT POINT on INDEX ActionMethod.







Press < CTRL + R > or < F5 > key to reload the view.








Above screenshot you can see pointer came.

Now we are going use OUTPUTCACHE ATTRIBUTE.


 [OutputCache(Duration = 60)]






Switch to Index.Cshtml file and Press < F5 > to execute project.

CACHE TESTING STEPS :
First time break point will be triggered.

Now press CTRL + R or F5 key , break point will not be trigger because CACHE is working.

After 60 seconds , press CTRL + R or F5 key,  break point will be trigger because we had given 60 seconds time limit.

After 60 seconds this will generate the member list by fetching from server.



If you press < F12 > key on OUTPUTCACHE you will come to know about detailed metadata of class.

















Full Source code:

MemberController.cs  code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace AspNetMvcCache.Controllers
{
    public class MemberController : Controller
    {
        // GET: Member
        //For 60 Seconds it will not reload list from the server.
        //List will come from CACHE.
        [OutputCache(Duration = 60)]
        public ActionResult Index()
        {
            //Create instance of LINQ To SQL class
            MemberDataClassesDataContext db = new MemberDataClassesDataContext();

            //Fetch Members records in list collection format
            var MemberList = (from a in db.tblMembers
                              select a).ToList();

            //returning MemberList to View
            return View(MemberList);
        }

        // GET: Member/Details/5
        public ActionResult Details(int id)
        {
            return View();
        }

        // GET: Member/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Member/Create
        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Member/Edit/5
        public ActionResult Edit(int id)
        {
            return View();
        }

        // POST: Member/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: Member/Delete/5
        public ActionResult Delete(int id)
        {
            return View();
        }

        // POST: Member/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}


Index.cshtml  code:

@model IEnumerable<AspNetMvcCache.tblMember>

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.MemberName)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.PhoneNumber)
            </th>
            <th></th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.MemberName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PhoneNumber)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.MemberID }) |
                @Html.ActionLink("Details", "Details", new { id=item.MemberID }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.MemberID })
            </td>
        </tr>
    }
    
    </table>
</body>
</html>






Happy Coding. .