In this article, we shall learn how to cache the user control data or how to implement partial/fragment caching in asp.net.
As per MSDN, A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.
In this article, let us learn how to implement partial/fragment caching in asp.net. This is achieved by caching the user control output. To cache the user control data, we can follow this approach.
Here is hundreds of .NET Tips and Tricks, you can also get online ASP.NET training here.
Lets first create a user control.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CahceUserControl.ascx.cs"
<%@ OutputCache Duration="5" VaryByParam="None" %>
<p><asp:Label ID="lblTime" runat="server" EnableViewState="false"
ASCX CODE BEHIND
protected void Page_Load(object sender, EventArgs e)
lblTime.Text = DateTime.Now.ToString();
Now create a .aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CahcedControl.aspx.cs"
<%@ Register Src="~/CahceUserControl.ascx" TagPrefix="uc1" TagName="UserControl" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<form id="form1" runat="server">
Try to refresh this page, the Date time doesn't change. Keep refreshing and after
5 seconds you should see the change in time.
<uc1:UserControl runat="server" ID="uc11" />
In the above code snippet, we have an asp:Label control in the user control and we are writing the current Date Time in the Page_Load method of the user control. That user control is being used into the CachedControl.aspx page. So normally every time the .aspx page refreshes, the DateTime should change but as we have kept the OutputCache directives onto the user control and specified duration as "5", the User control output data will be cached for 5 seconds. So till 5 seconds of the first request even if the page is refreshed the DateTime value doesn’t change on the page. After 5 seconds the user control is processed again on the server and fresh data is cached and subsequent request till next 5 seconds is served from the Cache again.
Notice that there is another parameter in the OutputCache directive of the User Control called VarByParam that is set to "None" here, we will discuss about this parameter in our forthcoming article.
In this way, we are just caching the fragment of the page. The whole page executes on the server but the user control data comes from the cache as due to OutputCache directive it doesn't executes every time.
Hope this article would be of use in understanding the partial/fragment caching in ASP.NET.
Thanks for reading, do let me know your comment or feedback. Keep reading and sharing your knowledge!