Recipe 13.5 Caching User Controls
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.
Add the @ OutputCache directive at the top of each .ascx file of the user controls you want to cache:
<%@ OutputCache Duration="5" VaryByParam="None" %>
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 the ability to cache user controls as a function of the property values. A more practical example (but much longer) would be the implementation of a global navigation bar that incorporates different images as a function of the page currently displayed in the application.
| || |
When caching user controls in pages, it is important to verify that the control is valid before accessing any properties of the control. When the page is first displayed, the user control will be created and will be available to the page. Subsequent page requests , while the user control is in the cache, will not create the control and the variable used to reference the control will be set to " Nothing " (VB) or " null " (C#). Attempts to access the user control without checking its validity will result in a null reference exception being thrown.
13.5.4 See Also