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.
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" %> …
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 cache will be sent to the browser. If the parameter values do not match, the page will be rendered by your code, added to the cache, and sent to the browser.
In our example, the VaryByParam attribute is set to DistrictID;SchoolID, which causes ASP.NET to check the URL of each page request for the DistrictID and SchoolID parameters in the query string. An example URL is shown here:
When ASP.NET receives the request for this page, it will check to see if a copy of the page exists in the cache for DistrictID=1 and SchoolID=2. If the copy exists in the cache, it will be sent to the browser without rerendering the page, which can improve your application's responsiveness, especially if database access was required to render the page. If a copy for DistrictID=1 and SchoolID=2 is not in the cache, the page will be rendered by the server.
This recipe deals with how to cache different versions of a rendered page as a function of its query string parameters. This same approach can be used to cache different versions of a page depending on form data when the page is posted back to the server. To cache versions as a function of posted parameters, use the names of the controls on the form (text boxes, checkboxes, and the like) in the VaryByParam attribute.