Fragment Caching: Caching Part of a Page

All the examples shown so far have cached the entire page. Sometimes all you want to cache is part of the page. To do this, wrap that portion of the page you want to cache in a user control and cache the user control. This is known as fragment caching. (For a complete discussion of user controls, see Chapter 15.)

For example, suppose you develop a stock portfolio analysis page, where the top portion of the page displays the contents of the user’s stock portfolio and the bottom portion contains a data grid showing historical data about one specific stock. There would be little benefit in caching the top portion of the page because it will differ for every user. However, it is likely that in a heavily used website, many people will be requesting historical information about the same stock, so there would be a benefit to caching the bottom portion of the page. This is especially true because generating the historical data requires a relatively expensive database query. In this case, you can wrap the data grid in a user control and cache just that.

To demonstrate fragment caching, add to the C17_Caching website a new web form called FragmentCaching.aspx and a new user control called SimpleUserControl.ascx, which will be cached in the page. This control will do no more than display the current time, as with previous examples, so add a Label control to show the time and an @OutputCache directive with a Duration of 10 seconds, as shown here:

<%@ Control ...

Get Programming ASP.NET 3.5, 4th 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.