ASP.NET Substitution Control


G04B0063

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"
 text="Label"></asp:label>

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();
}

W

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.

Ads by Lake Quincy Media

Other Related Items:

Backpackers' Cache - Carrying CaseBackpackers' Cache - Carrying CaseThis carrier is specifically designed to carry the Backpackers' Cache Bear Resistant Canister by Garcia Machine. The standard in bear proof food containers.
How to Break an Egg: 1,453 Kitchen Tips, Food Fixes, Emergency Substitutions, and Handy TechniquesHow to Break an Egg: 1,453 Kitchen Tips, Food Fixes, Emergency Substitutions, and Handy TechniquesNeed a cool way to handle hot chiles? Looking to cut down on kitchen clean-up? Let the readers, contributors, and editors of "Fine Cooking" magazine s... Read More >

Related Post

Comments are closed.

DotNetNuke Sponsor

 

Most Valuable Blogger
Sponsor