O'Reilly logo

ASP.NET 2.0: A Developer's Notebook by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cache Fragments of a Page

Note

You can now cache portions of a page, instead of the entire page, and thereby speed up page updates.

In ASP.NET 1.x, you can either cache an entire page or cache fragments of the page using user controls. In ASP.NET 2.0, you can cache the output of a page while designating a portion of the page to be updated on every request.

How do I do that?

In this lab, you will create a page that uses fragment caching. The main page will use output caching, while a part of the page will be updated on every request.

  1. Launch Visual Studio and create a new web site project. Name the project C:\ASPNET20\chap06-CacheFragments.

  2. In the default Web Form, switch to Source View and add the @OutputCache directive. You will cache the output of this page for five seconds:

    <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 
    Inherits="Default_aspx" %>
    <%@ OutputCache Duration="5" VaryByParam = "none" %>
                      
  3. Switch to the code-behind of default Web Form. In the Page_Load event, type the following code:

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load
        Response.Write("Current (cached) Time is :" & Now)
    End Sub
  4. The output of the Write statement will be cached for five seconds, meaning the time will be updated every five seconds. Now, add a shared function in the default Web Form that also displays the current time:

    Public Shared Function getServerTime( _ ByVal context As System.Web.HttpContext) _ As String Return "Current ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required