Recipe 16.7. 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 the same as that described in Recipe 16.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 unavailable 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 5.1 and 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 be cached for every combination of the headerImage, dividerColor, and dividerHeight property values used in the application.

Though 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 but longer example 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, 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 residing 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#). If your code attempts to access the user control without first checking the control's validity, a null reference exception will be thrown.

See Also

Recipe 5.1

ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: