Wednesday, 14 December 2011

OutputCache - Substitution

With ASP.NET version 1.0 and 1.1, there was no way to control which parts of a page would be cached, and more importantly: Which parts would be generated on each request no matter what. That meant that whenever you needed just a small part of the page to refreshed on each request, the OutputCache directive could not be used. This has changed with ASP.NET 2.0, where we may use the tag to make areas exist outside the cached content. Have a look at the following example:
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ OutputCache duration="120" varybyparam="None" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Caching</title>
</head>
<body>
    <form id="form1" runat="server">
        Cached datestamp:<br />
        <%= DateTime.Now.ToString() %><br /><br />
        Fresh datestamp:<br />
        <asp:Substitution runat="server" id="UnCachedArea" methodname="GetFreshDateTime" />
    </form>
</body>
</html> 
The Substitution tag takes an attribute called methodname, which holds the name of a method which should return the string to output. Once the page is loaded, no matter if it's returned from the cache or freshly generated, this method will be called, and the Substitution control will be filled with the returned string. Here is the CodeBehind, where you will see our GetFreshDateTime method:
using System;
using System.Data;
using System.Web;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected static string GetFreshDateTime(HttpContext context)
    {
        return DateTime.Now.ToString();
    }
}
Since the GetFreshDateTime method needs to be called by the Substitution control, it needs to "look" a certain way - it has to take the HttpContext as a parameter, it has to return a string, and it has to be static. Now, the HttpContext allows you to access all kinds of information about the request etc. to use for returning the proper value. For now, we simply return the current datetime. Run the example, and see how the first datestamp is cached, while the second is reloaded each time. It's as simple as that!

No comments:

Post a Comment