Just as whole pages can be cached, ASP.NET supports caching UserControls
as well. Imagine your job is to create a sizable Web site that allows
users to navigate through information using 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 might 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 UserControl and apply the OutputCache directive to the UserControl. Doing so causes ASP.NET to cache the portion of the page represented by the control.
The OutputDirective can be applied to the ASCX file that makes up a UserControl. The OutputDirective for a UserControl can 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 how to cache the output of a UserControl.
Caching the output of user controls
Create a simple UserControl
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 UserControl, 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 UserControl from Solution Explorer onto the UseSiteMenuControl page. When ASP.NET loads and runs your Web page, ASP.NET caches the UserControl because the UserControl 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 that
the entire control tree was rendered. Press 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 rerendering the entire SiteMenu control.