Caching a user control in ASP.NET?

Prashant picture Prashant · Feb 20, 2009 · Viewed 14.5k times · Source

I have created a user control in my application "header.ascx", I am pasing a selectedMenu attribute to this control on which the control selects the selectedMenu value specified. Suppose, I have passed value "home" or "search" then it will select (highlight it) the search menu.

I want to cache this control, When the value of the selectedMenu attribute changes then only the cache will be refreshed else it should picks up the control from cache??

Is it possible to cache a user control in asp.net?? I am using ASP.NET 2.0 (C#)

Answer

Helephant picture Helephant · Feb 20, 2009

User control caching in ASP.NET is called fragment caching. It's done by adding an OutputCache directive to the top of your page:

You can't vary the cache by setting the property on the control because the control isn't actually created if it's found in the cache. If you try to access the control in the code behind it's cached, it will be null.

Is the condition that determines whether the control should be cached or not something that you can determine by looking at the current request? If it is, you can use the varybycustom attribute (http://msdn.microsoft.com/en-us/library/system.web.ui.partialcachingattribute.varybycustom.aspx) of the output cache directive. You can put any string you want in there as the parameter and then when the caching is evaluated the GetVaryByCustomString() method from Global.asxa will be called and you can put the logic for whether the control should be cached or not there.