TOC

This article is currently in the process of being translated into Spanish (~35% done).

Caching:

OutputCache - Substitution

Con la versión 1.0 y 1.1 de ASP.NET, no había manera de controlar que partes de la pagina se almacenarían en cache, y aun más importante: Cuales partes serian generadas en cada petición sin importar que. Eso significaba que siempre que se necesitara que solo una pequeña parte de la página sea refrescada en cada petición, la directiva OutputCache no podía ser usada. Esto ha cambiado con ASP.NET 2.0, donde podemos usar el tag <asp:Substitution> para hacer que áreas existan fuera del contenido en cache. Hecha un vistazo al siguiente ejemplo:

<%@ 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!


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!