开发者

Vary output caching on usercontrol by clientID

开发者 https://www.devze.com 2023-04-11 00:38 出处:网络
I have a user control which I would like to use output caching on, but it is used several times with different data.

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" D开发者_开发技巧uration="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 because ToString will 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 same ToString() value.
Second issue is that DateTime.Now is 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.


Nest them inside another user control and put instances of that where ever you want it to be cached.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号