Datasheet
Using the Substitution Control
ASP.NET 2.0 provides a new control called the Substitution control, which enables you to insert
dynamic content into a cached web page. For example, you can display the name of an end user, which
is dynamically generated in a cached web page containing some text or images. The
Substitution con-
trol provides a property called
MethodName, which represents the method called to return the dynamic
content. Listing 1-4 shows an example of the
Substitution control in action.
Listing 1-4: Partial Page Caching Using Substitution Control
<%@ Page Language=”C#” %>
<%@ OutputCache Duration=”6000” VaryByParam=”none” %>
<script runat=”server”>
static string GetRandomNumber(HttpContext context)
{
int randomNumber;
randomNumber = new System.Random().Next(1, 10000);
return randomNumber.ToString();
}
</script>
<html>
<head>
<title>Use of Substitution control to implement Partial Caching</title>
</head>
<body>
<form id=”form1” runat=”server”>
The random number generated is:
<asp:Substitution ID=”Substitution1” MethodName=”GetRandomNumber”
Runat=”Server” />
<p>
The current time is <%= DateTime.Now.ToString(“t”) %>.
It never changes since the page is cached.
</p>
</form>
</body>
</html>
At the top of the page, the OutputCache directive is used to cache the contents of the page in memory.
The
Duration attribute of the OutputCache directive is set to 6000 milliseconds. The VaryByParam
attribute indicates whether or not ASP.NET should consider the parameters passed to the page when
caching. When
VaryByParam is set to none, no parameters will be considered; all users will receive the
same page no matter what additional parameters are supplied. The
MethodName attribute of the
Substitution control is set to a method named GetRandomNumber, which simply returns a random
number between 1 and 10,000. Note that the return value of the
GetRandomNumber method is a string,
because the
HttpResponseSubstitutionCallback delegate always requires a return type of string.
When you make a request for the page through the browser, you will find that the displayed current
time always remains the same, whereas the portion of the page that is generated by the substitution con-
trol keeps changing every time. In this case, it displays a random number between 1 and 10,000 every
time someone requests the page.
22
Part I: Introduction
05_041796 ch01.qxp 12/29/06 9:09 PM Page 22