What is ASP.NET Caching? How to use Caching in ASP.NET ?
In this article I am going to explain about what is caching in ASP.NET and how to use three types of Caching in ASP.NET. I explained here in detail with example code.
Description :
Caching is used to keep whole page or partial page or some values in cache in web pages in specified time. This caching is used to speed up performance of paging.Three types of caching available in ASP.NET
1) Page level caching (also called as Output Caching)
2) Page fragment caching (also called as partial page output caching)
3) Programmatic or data caching Declaration of cache in ASP.NET
You can declare cache and its duration using below single line in ASP.NET
<%@OutputCache Duration="10" VaryByParam="none" %>
OutputCache Attributes
1. Duration:
It is defined as how many seconds this page is keep in cache.
2. Location
This is used to define where the cache can be stored like client browser or server etc.
Location values
Any
This is the default value of cache if user not mention values. This is store cache values in the browser clientor on the server where the request was processed.
Client
This client value is used to store cache in client's browser.
Downstream
This one is used to store in HTTP 1.1 cache-capable devices other than the origin server
None
The one is used to disabled cache for the requested page.
Server
The output cache is located on the Web server where the request was processed.
ServerAndClient
The server and client values are used to store only at the origin server or the requesting client. Proxy servers are not allowed to cache the response.
3. Shared
This is used to definewhether user control output can be shared with multiple pages or not. The default value is false.
4. VaryByCustom
It is used to set any text that represents custom output caching requirements. It used to set cache based on browse rand its version detail etc.
5. VaryByParam:
It is used to defined any GET or POST methods are used in the cache or not. This can be used in dynamic pages like ASP.NET pages to indicate query string values are passed or not.
VaryByParam values
• None
• *
• query string variable name
For example,
In dynamic pages we are passing query string, like first user is see the employee no 101 query string like become /EmpDetails.aspx?eno=101 and this values are stored in cache. If second user want to see 102 details that time we need to show 102 employee details. If you set VaryByParam="none" in output cache then only shows 101 old cached employee details. So avoid this kind of problem in dynamic pages set output cache as like VaryByParam="eno" or VaryByParam="*". This one is help to know current requried employee details when page is stored in cache.
6. VaryByControl
It is used to define webuser control id in the .ascx page, this attribute not support in the .aspx page. 1) Page level Caching (Output caching):
The page level caching is defined as store whole page content in cache at specified time. That page is stored in the cache when load first time. Then you can call that page again that request cannot go to server instead of that load data from caching. This increase performance of the page. It is easy to implement in ASP.NET pages .Example:
Client side:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@OutputCache Duration="10" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
Code Behind:
protectedvoid Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now.ToString());
}
In the above example put break point on page load and run the above page. After you run that page Date and time display in the we page. Then refresh your page frequently hitting F5 button or right click on the page refresh. Noticed that the date time is not changed in till 10 seconds because we are write in the client side top output cache.
<%@OutputCache Duration="10" VaryByParam="none" %>
This output cache is stored this page till 10 seconds , so whenever you hit F5 or click page refresh it display content from the cache, the request cannot go back to server. After 10 seconds if you press F5 then request goto server and display refreshed time in that page. 2) Page fragment caching (partial page output caching)
Page fragment caching is allowed to store particular part of page in the cache. For example you can write header text in web user control then you are used that control in all the web pages as a header. Use Page fragment caching in web user control that time to avoid request to server again and again.
This one is avoid webuser control request mean in whole page particular part of the webuser control is stored in cache this is defined as fragment caching in the ASP.NET
Example
First step I have create webusercontrol.ascx page with outputcache tag prefix like below
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<%@OutputCache Duration="5" VaryByControl="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
In the above code I have declare VaryByControl="WebUserControl" name so partial cache as webuser control
Code behind
In code behind display time in label
protectedvoid Page_Load(object sender, EventArgs e)
{
Label1.Text = "<br/> Control Level Cahce" + DateTime.Now.ToString() + "<br/>";
}
Second step I have create .aspx page and implement that webuser control and also here write date-time in one variable
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<%@ Register src="WebUserControl.ascx" tagname="WebUserControl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
Code Behind
protectedvoid Page_Load(object sender, EventArgs e)
{
Label1.Text="<br/> Page Level Cahce" + DateTime.Now.ToString() + "<br/>";
}
Consider above example I have used two label (one is in webusercontrol.ascx, another one label is in .aspx page) controls
I have set cache in the .ascx page duration is 5 second.So that .ascx page label is stored in cache not change time only aftr five second. But in the normal .aspx page label time is change every time when press F5 to refresh check it.3) Programmatic or data caching
This kind of cache is stored data like value, dataset, data table etc. in the ASP.NET page.Example1
In this example I store create cache with the key "dte" and assign date time. Then get value from that cache bind it in the label. After bind remove that label.
protectedvoid Page_Load(object sender, EventArgs e)
{
//Create cache like below
Cache["dte"] = DateTime.Now.ToString();
//Get value from cache below
Label1.Text = Cache["dte"].ToString();
//Remove cache and its value like below
Cache.Remove("dte");
}Example2:
Here I have store dataset in cache and retrieve back that dataset from cache value
protectedvoid Button1_Click(object sender, EventArgs e)
{
DataTable dt = newDataTable();
DataRow dr;
dt.Columns.Add("eno");
dt.Columns.Add("empname");
dr = dt.NewRow();
dr["eno"]="101";
dr["empname"]="Ravindran";
dt.Rows.Add(dr);
//Assign dataet to cache
Cache["dt"] = dt;
//Get back that dataset here like below
GridView1.DataSource = (DataTable)Cache["dt"];
GridView1.DataBind();
Cache.Remove("dt");
}
In ASP.NET Provide insert method to insert key and value directly. Insert method have more overload parameter like below
1. Cache.Insert(key, value):
This is used to insert cache name and its value like below
//Insert cache with name and its value
Cache.Insert("t1", "test");
2. Cache.Insert(key, value, dependencies):
//Insert cache with name, its value and dependencies
Cache.Insert("t2", "test", null);
3. Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration);
//Insert cache with name, its value and dependencies, Expiration
Cache.Insert("t3", "test", null, DateTime.MaxValue, TimeSpan.FromMinutes(10));
slidingExpiration is used to remove cache when the cache is not used till 10min in the above example code.Source code:
Client Side: ASP.NET
Code Behind: C#Conclusion
I hope this article is help you to know about caching concept in ASP.NET.
More than one partial page caching in single page asp.net is it possible ?