16.2. Caching Pages Based on Query String Parameter Values

Problem

You want to use page caching to improve the performance of your application, but the contents of your pages vary depending on the values of parameters in the query string.

Solution

Add the @ OutputCache directive to the .aspx file of each page you want to cache with the VaryByParam attribute set to the names of the parameters used in the query string:

	<%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master"
         AutoEventWireup="false"
		 CodeFile="CH16CachePageByQuerystringVB.aspx.vb"
		 Inherits="ASPNetCookbook.VBExamples.CH16CachePageByQuerystringVB"
		 Title="Cache Page By Querystring" %>
    <%@ OutputCache Duration="10" VaryByParam="DistrictID;SchoolID" %>

               …

Discussion

Programmers commonly pass information in the query string that is used to define what is displayed on a page. Because the page content is dependent on one or more parameters, the basic caching example shown in Recipe 16.1 cannot be used. Fortunately, ASP.NET provides the ability to cache multiple copies of a page by defining the dependent parameters.

You define the parameters ASP.NET will use to cache copies of a page by setting the VaryByParam attribute to a semicolon-separated list of the parameters used in the query string to define the page contents. For each page request, ASP.NET checks the values of the indicated parameters in the query string. If the parameter values match the parameter values of a copy of the page in the cache, the copy from the ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.