Just as whole pages may be cached, ASP.NET supports caching User Controls as well. Imagine your job is to create a sizeable Web site that allows users to navigate through information via various navigation controls (menus, hyperlinks, and so forth). For example, imagine a part of your page shows links or other navigation controls that lead users to the most recent news, summary information, and other places. The actual content may change, but the links probably don't. If the links don't change very often and the cost of generating that section of the page is expensive, it makes sense to move the functionality into a User Control and apply the OutputCache directive to the User Control. Doing so will cause ASP.NET to cache the portion of the page represented by the control.
The OutputDirective may be applied to the ASCX file that comprises a User Control. The OutputDirective for a User Control may also use the Shared property to tell ASP.NET to cache one version of the control for all pages that use it, resulting in potentially even higher performance over the span of many hits (the default is false).
The following exercise illustrates caching the output of a User Control.
Create a simple User control for the OutputCaching project. Navigation controls are perfect for caching, so create a control that has a menu. Name the control SiteMenu.ascx. Drag a Menu control onto the User Control, as shown here:
Add some menu items, as shown in this graphic:
Add the OutputCache directive with the following parameters in the control source, like so:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="SiteMenu.ascx.cs" Inherits="SiteMenu" %> <%@ OutputCache Duration="60" VaryByParam="none" %>
Create a new page in the project. Name it UseSiteMenuControl.aspx.
Drag the SiteMenu User Control onto the UseSiteMenuControl page. When ASP.NET loads and runs your Web page, ASP.NET will cache the User Control because the User Control mentions the OutputDirective.
Make sure tracing is turned on in the UseSiteMenuControl.aspx file. (That is, set the Trace="true" attribute in the Page directive.) Surf to the page. The first time you surf to the page, you'll see the following information in the control tree section of the Trace output:
Notice the entire control tree was rendered. Push the refresh key (F5 in Internet Explorer) while looking at UseSiteMenuControl.aspx. Examine the control tree portion of the Trace output again. Notice that ASP.NET uses the cached control instead of re-rendering the entire SiteMenu control.