Caching User Controls

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.

User Controls and Output Caching

  1. 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:

  2. 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" %>
  3. Create a new page in the project. Name it UseSiteMenuControl.aspx.

  4. 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.

  5. 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.


by BrainBellupdated