13.5. Caching User Controls
Problem
You have data-entry pages in your application that cannot be cached, but the pages contain user controls that do not change and you want to cache them.
Solution
Add the @ OutputCache
directive at the top of each
.ascx
file of the user controls you want to
cache:
<%@ OutputCache Duration="5" VaryByParam="None" %>
Discussion
This solution is exactly the same as that described in Recipe 13.1, except that it is applied to a user control. In fact, all of the solutions described previously in this chapter can be applied to user controls.
User controls have one caching feature that is not available to pages. A user control can be cached as a function of its properties. This is quite handy because many times a user control, like a header or global navigation bar, varies as a function of its properties, not the parameters passed to the page on which it is used.
To see this in action for yourself, we suggest implementing the user
control example described in Recipe 4.1, and then adding the @OutputCache
directive shown here at the top of the
.ascx
file for the header user control:
<%@ OutputCache Duration="15" VaryByControl="headerImage;dividerColor;dividerHeight" %>
A copy of the user control will then be cached for every combination
of the headerImage
,
dividerColor
, and dividerHeight
property values used in the application.
While this example is not all that useful, since the header on a page is generally consistent within an application, the example demonstrates ...
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.