Export (0) Print
Expand All

Substitution Web Server Control Overview 

The Substitution control is used on ASP.NET Web pages that are configured to be cached. The Substitution control allows you to create areas on the page that can be updated dynamically and then integrated into the cached page.

Dynamically Updating Portions of a Cached Page

When an ASP.NET page is cached, the entire output of the page is cached by default. On the first request, the page runs and caches its output. On subsequent requests, the request is fulfilled from the cache and code on the page does not run.

In some circumstances, you might want to cache an ASP.NET page but update selected portions of the page on each request. For example, you might want to cache the majority of a page but be able to dynamically update time-sensitive information on the page.

You can use the Substitution control to insert dynamic content into the cached page. The Substitution control does not render any markup. Instead, you bind the control to a method on the page or parent user control. You create the static method yourself, returning any information that you want to insert into the page. The method called by the Substitution control must meet the following criteria:

  • It is defined as a static method (shared in Visual Basic).

  • It accepts a parameter of type HttpContext.

  • It returns a value of type String.

Note that other controls on the page are not accessible to the Substitution control—that is, you cannot examine or change the value of other controls. However, the code does have access to the current page context using the parameter passed to it.

When the page runs, the Substitution control calls the method and then substitutes the return value from the method for the Substitution control on the page.

The following code example shows how to use the Substitution control to create dynamically updated content on a cached page. Code in the page's Load event updates a Label control with the current time. Because the page's cache duration is set to 60 seconds, the text of the Label control does not change even if the page is requested multiple times during the 60-second period. A Substitution control on the page calls the static method GetTime, which returns the current time as a string. Each time the page is refreshed, the value represented by the Substitution control is updated.

<%@ Page Language="C#" %>
<%@ OutputCache Duration=60 VaryByParam="None" %>

<script runat="server">
    void Page_Load()
        Label1.Text = DateTime.Now.ToString();
    public static String GetTime(HttpContext context)
      return DateTime.Now.ToString();
<head runat="server"></head>
    <form id="form1" runat="server">
    <asp:Label runat="server" ID="Label1" />
    <asp:Substitution runat="server" 
        MethodName="GetTime" />
    <asp:Button runat="server" ID="Button1" Text="Submit"/>

See Also

Community Additions

© 2014 Microsoft