13.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, as shown here:

 <%@ Page Language="vb" AutoEventWireup="false" 
         Codebehind="CH13CachePageByQuerystringVB.aspx.vb" 
         Inherits="ASPNetCookbook.VBExamples.CH13CachePageByQuerystringVB" %>
<%@ OutputCache Duration="10" VaryByParam="DistrictID;SchoolID" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
  ...
</html>

Discussion

It is fairly common practice to pass information in the query string that is used to define what is displayed on a page. Because the page content is dependent upon one or more parameters, the basic caching example shown in Recipe 13.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 ...

Get ASP.NET Cookbook 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.