Use VaryByControl for Smart User Control Caching

Cache different versions of a user control.

Jeff Prosise

October 30, 2009

2 Min Read
ITPro Today logo in a gray background | ITPro Today

ASP.NET's page output cache, which you can controldeclaratively with @ OutputCache directives, helps you optimize performance bypreventing pages and user controls that contain relatively static content frombeing re-rendered unnecessarily. Placing this directive in an .aspx file letsASP.NET cache the page's output for 60 seconds at a time:

<%@ OutputCache Duration="60"VaryByParam="None" %>

Placing the same directive in an .ascx file allows onlythe output from that file to be cached without affecting whether other contenton the page can be cached.

When used in an .ascx file, the @ OutputCache directivesupports an attribute named VaryByControl. VaryByControl is more than aconvenience - it's an outright necessity in some user controls. Unfortunately,the documentation is of little help in deciphering VaryByControl's meaning.VaryByControl lets you cache different versions of a user control based onvariances in the properties of controls contained in the user control. As anexample, consider this .ascx file:

<%@ OutputCache Duration="60"  VaryByControl="MyDropDownList" %>            

This user control declares two Web controls: aDropDownList control and a Label control. When the dropdown list fires aSelectedIndexChanged event, the OnUpdateLabel method updates the Label controlto echo the item now selected in the dropdown list. Without VaryByControl, youcouldn't cache this user control because the output cached the first time thecontrol executes would include the output from the Label control and would notchange until the cached output is discarded. VaryByControl fixes this problemby configuring ASP.NET to cache different versions of the control's outputbased on varying property values (in this case, on varying values ofMyDropDownList.SelectedIndex) in the control or controls the user controlcontains. Simply identify the control or controls whose property values affectthe rendering of the user control in a VaryByControl attribute and even usercontrols that vary their output based on the state of embedded controlssuddenly become cache-compatible.

 

Jeff Prosise isauthor of several books, including ProgrammingMicrosoft .NET (Microsoft Press). He also is a co-founder of Wintellect(http://www.wintellect.com),a software consulting and education firm that specializes in .NET. Got aquestion for this column? Submit queries to [email protected].

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like