What is Fragment Caching in Asp.Net?
Fragment caching means cache only particular portion of the web page. This fragment caching can be achieved by using user controls (.ascx) in web form. In asp.net for each user control we can set cache durations separately.
To achieve fragment caching first create one user control (.ascx) in your application for that Right click on your application --> Select Add --> Add New Item --> Select Web User Control --> Give name and Click OK.
Now open user control and write the code like as shown below.
WebUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"Inherits="WebUserControl" %>
<%@ OutputCache Duration="5" VaryByParam="None" %>
<asp:Label ID="lblTime" runat="server" Font-Bold="true" ForeColor="Blue" />
|
If you observe above code here we are caching user control for “5” seconds by using “OutputCache” property. This user control values will update only after every “5” seconds even if continuously refresh page. Now open WebUserControl.ascx.cs code behind file and write the following code
protected void Page_Load(object sender, EventArgs e)
{
lblTime.Text = DateTime.Now.ToString();
}
|
Now drag and drop user control to your aspx page in Design mode or write the code like as shown below to add user control to aspx page.
<%@ 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>Fragment Caching in Asp.Net with Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>Refresh the Page Time Will Update Only After Every 5 Seconds</p>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
</div>
</form>
</body>
</html>
|
No comments:
Post a Comment