I have a user control which I would like to use output caching on, but it is used several times with different data.
I thought about using VaryByCustom and try to receive the ClientID of the control, but haven’t been able to find a way.
Is there a way to output cache a usercontrol based on the ClientID, or another way to identify it by its position in the DOM?
Update:
I have tried to add a hidden field and set the output caching. For the example I have set the value of the hidden field to Datetime.Now, but it still displays the same usercontrol, and not two who are different by the content.
<%@ OutputCache VaryByControl="hidMyField" Duration="120" %>
<asp:HiddenField runat="server" ID="hidMyField" Value="<%= Datetime.Now.ToString() %>"/>
One of the way could be to have a server side hidden field on the control, push the user control’s client ID into it and then use VaryByControl parameter with hidden field’s ID.
For more information/options, see this MSDN link that discusses the same problem.
EDIT
Using
Datetime.Now.ToString()is not a good idea for two reasons! If you see the actual value for various controls, you will find it to be the same becauseToStringwill have value up to seconds – all your control instances on the page will have almost same date/time value probably differing in milli-seconds which will give sameToString()value.Second issue is that
DateTime.Nowis non-deterministic. For caching to work, you need to have deterministic value (a value that does not changes in repeated calls) – otherwise for every page request, you will have a different value which will invalidate the cache. I suggest putting user control’s client id as a value. Yet another way would be expose a property in user control and set it to running number such as 1,2,3.. from the page.