ASP.NET Substitution Control


Tucked away on the toolbar is a little-used and often overlooked control.  Not using this control could be costing you in performance.

The control I’m referring to is the Substitution control.  The only time you’d use it would be if you had implemented page caching.  You are using page caching, right?

What?  You aren’t because you have a section of each page that needs to be updated, otherwise you would?

That is exactly what the substitution control was made for.

Create an ASPX page and implement caching at the top

<%@ OutputCache Duration="60" VaryByParam="None"%>

Now put a label on the page

<asp:label id="m_labelDate" runat="server"

in the page_load event handler, set the date and time into the label

protected void Page_Load(object sender, EventArgs e)
    m_labelDate.Text = DateTime.Now.ToLongTimeString();

If you run this now, you’ll see that no matter  how many times you refresh the page, the time will stay the same for a minute.  Once the minute is up, the time will change.  This is because the page is being retrieved from the cache each time.

To implement caching and get the date to update, you’ll want to use the Substitution control.  We’ll need to implement a static method in the page class for this to work first.

public static string CurrentTimeString(HttpContext context)
    return DateTime.Now.ToLongTimeString();


e didn’t use it here, but notice that we are passing in the HttpContext which will allow us to access items like the session object.

Now place the substitution control on the page and tell it to call the CurrentTimeString method we created above.

<asp:Substitution ID="Substitution1"
runat="server" MethodName="CurrentTimeString" />

Now every time you refresh the page, you’ll get the new time, but all that will get called of the page code is the static method.  You can see this best by leaving the label in when you put in the substitution control.  The label will stay the same and the substitution control will change.

Related Post

Leave a Reply

Comment Policy:

  • You must verify your comment by responding to the automated email that is sent to your email address. Unverified comments will never show.Leave a good comment that adds to the conversation and I'll leave your link in.
  • Leave me pure spam and I'll delete it.
  • Leave a general comment and I'll remove the link but keep the comment.

Notify me of followup comments via e-mail