Microsoft KB Archive/308378

= How To Perform Fragment Caching in ASP.NET by Using Visual C# .NET =

Article ID: 308378

Article Last Modified on 7/15/2004

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q308378



For a Microsoft Visual Basic .NET version of this article, see 308645.

IN THIS TASK
SUMMARY Requirements Create an ASP.NET Web Application Using C# .NET Create the User Controls
 * User Control 1 (FragmentCtrl.ascx)
 * User Control 2 (FragmentCtrl2.ascx)

Create the Web Form to Contain the User Controls Run the Sample Troubleshooting REFERENCES



SUMMARY
This article demonstrates how to implement fragment caching in ASP.NET. Fragment caching does not actually cache a Web Form's code fragments directly; fragment caching refers to the caching of individual user controls (.ascx) within a Web Form. Each user control can have independent cache durations and implementations of how the caching behavior is to be applied. The sample code in this article illustrates how to achieve this functionality.

Fragment caching is useful when you need to cache only a subset of a page. Navigation bars, header, and footers are good candidates for fragment caching.

back to the top

Requirements

 * Microsoft Windows 2000
 * Microsoft Internet Information Server (IIS)
 * Microsoft .NET Framework
 * ASP.NET

back to the top

Create an ASP.NET Web Application Using C# .NET
The following steps demonstrate how to create a new ASP.NET Web application named FragmentCache.
 * 1) Open Microsoft Visual Studio .NET
 * 2) On the File menu, point to New, and then click Project.
 * 3) In the New Project dialog box, click Visual C# Projects under Project Types, and then click ASP.NET Web Application under Templates.
 * 4) In the Name box, type FragmentCache . In the Location box, select the appropriate server. If you are using the local server, you can leave the server name as http://localhost.

back to the top

Create the User Controls
This section provides the sample code and explanations of each user control that you will use in this article. You can copy and paste the sample code into the associated .ascx file and code-behind page as described.

back to the top

User Control 1 (FragmentCtrl1.ascx)
The following user control, FragmentCtrl1.ascx, is very simple. FragmentCtrl1.ascx writes out the time that the cache entry for the item occurs. As with all of the controls that are created for this article, a basic description is provided for the control to make it easier to distinguish the settings and the associated behaviors at run time in the later sections.  In Visual Studio .NET, create a new user control as follows:  In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control. Name the control FragmentCtrl1.ascx, and then click Open.  Make sure that the Design tab is selected. Click and drag a Web Form Label control from the Web Forms section of the toolbox, and drop the Label control onto the page. Click the Label control. In the Properties pane of the Visual Studio .NET integrated development environment (IDE), type CacheEntryTime in the ID property, and leave the Text property blank.  Switch to HTML view, and add the following @OutputCache directive to the top of the page: <%@ OutputCache Duration=&quot;40&quot; VaryByParam=&quot;none&quot;%> </li> Right-click the .ascx file, and then click View Code to display the code-behind page source.</li>  Add the following code to the Page_Load event, which sets the CacheEntryTime label's Text property: private void Page_Load(object sender, System.EventArgs e)     { CacheEntryTime.Text =&quot;FragmentCtrl1: &quot; + DateTime.Now.TimeOfDay.ToString; }                   </li></ol>

back to the top

User Control 2 (FragmentCtrl2.ascx)
Although you can simply create another version of the first control with a different cache duration to show how multiple user controls can have independent behaviors in the same page, this section makes the second control, FragmentCtrl2.ascx, more interesting. FragmentCtrl2.ascx is used to introduce the VaryByControl attribute. VaryByControl allows different cache entries to be made based on the values for a specified control. This functionality is made much clearer at run time in the next section.  In Visual Studio .NET, create a new user control as follows:  In Solution Explorer, right-click the project node, point to Add, and then click Add Web User Control.</li> Name the control FragmentCtrl2.ascx, and then click Open.</li></ol> </li> Make sure that the Design tab is selected. Click and drag a Web Form Label control from the Web Forms section of the toolbox, and then drop the Label control onto the page.</li> Click the Label control. In the Properties pane, type CacheEntryTime in the ID property, and leave the Text property blank.</li> Position the cursor directly after the Label control, and then press ENTER to move to the next line in the page.</li> Click and drag a Web Form RadioButtonList control from the Web Forms section of the toolbox, and drop it onto the page. The RadioButtonList control should appear by itself on the line after the Label control.</li> Click the RadioButtonList control. In the Properties pane, type MyRadioButtonList in the ID property.</li> In the Properties pane, locate the Items property for the MyRadioButtonList control, click Collection, and then click the ellipsis (...) button that appears next to Collection.</li> In the ListItem Collection Editor window, add ListItem members as follows:  <li>Under Members, click Add.</li> <li>In the ListItem properties section, set Text and Value to Yes, and set Selected to True.</li> <li>Under Members, click Add again.</li> <li>In the ListItem properties section, set Text and Value to No, and set Selected to False.</li> <li>Under Members, click Add one last time.</li> <li>In the ListItem properties section, set Text and Value to Maybe, and set Selected to False.</li> <li>Click OK to return to the .ascx file in Design view. Notice that three radio buttons appear that are contained within the RadioButtonList control: Yes, No, and Maybe.</li></ol> </li> <li>Position the cursor directly after the RadioButtonList control, and press ENTER to move to the next line in the page.</li> <li>Click and drag a Web Form Button control from the Web Forms section of the toolbox, and drop it onto the page. The Button control should appear by itself on the line after the RadioButtonList control.</li> <li>Click the Button control. In the Properties pane, type Submit in the Text property.</li> <li> Switch to HTML view, and add the following @OutputCache directive to the top of the page: <%@ OutputCache Duration=&quot;60&quot; VaryByParam=&quot;none&quot; VaryByControl=&quot;MyRadioButtonList&quot;%> </li> <li>Right-click the .ascx file, and then click View Code to display the code-behind page source.</li> <li> Add the following code to the Page_Load event, which sets the CacheEntryTime label's Text property: private void Page_Load(object sender, System.EventArgs e)     { CacheEntryTime.Text = &quot;FragmentCtrl2: &quot; + DateTime.Now.TimeOfDay.ToString; }                   </li></ol>

back to the top

Create the Web Form to Contain the User Controls
You can now create the Web Form (.aspx) to contain the newly developed user control. To create the Web Form, follow these steps: <ol> <li>Add a new Web Form named FragmentCaching.aspx to your project in Visual Studio .NET as follows: <ol style="list-style-type: lower-alpha;"> <li>In Solution Explorer, right-click the project node, point to Add, and then click Add Web Form.</li> <li>Name the Web Form FragmentCaching.aspx, and then click Open.</li></ol> </li> <li>Make sure that the Design tab is selected. Click and drag a Web Form Label control from the Web Forms section of the toolbox, and drop it onto the page.</li> <li>Click the Label control. In the Properties pane, type Time in the ID property, and leave the Text property blank.</li> <li>Position the cursor directly after the Label control, and press ENTER to move to the next line in the page.</li> <li>Drag FragmentCtrl1.ascx, and drop it onto the Web Form so that it is positioned after the Label control on a line by itself. Position the cursor directly after the control, and press ENTER to move to the next line in the page.</li> <li>Drag FragmentCtrl2.ascx, and drop it onto the Web Form so that it is positioned after FragmentCtrl1.ascx on a line by itself.</li> <li> In HTML view, the Web Form should appear similar to the following code: <%@ Page language =&quot;c#&quot; Codebehind=&quot;FragmentCaching.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;FragmentCache.FragmentCaching&quot; %> <%@ Register TagPrefix=&quot;uc1&quot; TagName=&quot;FragmentCtrl1&quot; Src=&quot;FragmentCtrl1.ascx&quot; %> <%@ Register TagPrefix=&quot;uc1&quot; TagName=&quot;FragmentCtrl2&quot; Src=&quot;FragmentCtrl2.ascx&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; > <HTML> <HEAD> <meta name=&quot;GENERATOR&quot; Content=&quot;Microsoft Visual Studio 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript (ECMAScript)&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <form id=&quot;FragmentCaching&quot; method=&quot;post&quot; runat=&quot;server&quot;> <P> WebForm Time: <asp:Label id=&quot;Time&quot; runat=&quot;server&quot; ForeColor=&quot;Blue&quot;></asp:Label> </P> <P> <uc1:FragmentCtrl1 id=&quot;FragmentCtrl11&quot; runat=&quot;server&quot;> </uc1:FragmentCtrl1> </P> <P> <uc1:FragmentCtrl2 id=&quot;FragmentCtrl21&quot; runat=&quot;server&quot;> </uc1:FragmentCtrl2> </P> </HTML> NOTE: Make sure that the controls are placed inside the </li> <li>Right-click the .aspx file, and then click View Code to display the code-behind page source.</li> <li> Add the following code to the Page_Load event, which sets the Time label's Text property: private void Page_Load(object sender, System.EventArgs e)     { Time.Text = &quot;WebFormTime: &quot; + DateTime.Now.TimeOfDay.ToString; }                   </li> <li>From the File menu, click Save All to save the user controls, the Web Form, and other associated project files.</li> <li>From the Build menu in the Visual Studio .NET integrated development environment (IDE), click Build to build the project.</li></ol>

back to the top

Run the Sample
This section demonstrates how to view the code at run time to witness the caching behavior and then briefly describes why the code performs the way that it does.
 * 1) In the Visual Studio .NET IDE Solution Explorer, right-click the FragmentCaching.aspx Web Form, and then click View in Browser to run the code.
 * 2) After the page appears in the browser, right-click the page, and then click Refresh to refresh the page. You can also press the F5 key to refresh the page if you are viewing the page in a browser that is external to the Visual Studio .NET IDE.

Notice that the time on the Web Form has been updated, but the user controls still display the time when their associated cache entry was made.
 * 1) In the second control, click Submit. Notice that the control displays an updated time. This is in response to the VaryByControl attribute setting for the user control that references the RadioButtonList control.
 * 2) Click No, and then click Submit again. Notice that the time is updated again in the user control's display. This is because a new cache entry is made for the control based on this No value setting.

Repeat this step except with the Maybe option. You see the same behavior.
 * 1) Click Yes, and then click Submit again. Repeat this operation with the No and Maybe options. Notice that these selections for the control are cached and that they display the previous cache entry time. If you continue to click Submit past the @ OutputCache directive's duration setting, the user control's time is updated for each specific value selection for the RadioButtonList control.

NOTE: It is not the goal of this article to cover all of the possible settings and scenarios for fragment caching. For more information, see the References section at the end of this article.

back to the top

Troubleshooting

 * Do not try to programmatically manipulate a user control that is output-cached. This is because the control is only dynamically created when it is run the first time before the cache entry occurs. The output cache satisfies all other requests until the control expires.
 * If the Web Form in which user controls are hosted has an output cache duration that is longer than the duration times of the user controls, the Web Form's setting dictates the caching behavior of the controls.

back to the top

<div class="references_section">