UserControl OutputCache and VaryByParam not working with postback!!
Don't know if anyone has come across this before. But if you
have a usercontrol that uses VaryByParam and you have it on
a page and do a postback you will get the wrong cache item.
Use the below test bed to see what I mean, this is following
to my
post for help on the asp.net forums, I then found
this
post which showed me it is an issue, following this I think
I came up with a solution. That is to add a hidden field to
my page with the name MenuID and populate that. Now on
postback it seems to work fine, as VaryByParam="MenuID"
seems to read the form var MenuID and gets the correct value
hence fixing caching.
Default.aspx
<form id="form1"
runat="server">
<uc1:WebUserControl1 ID="WebUserControl11" runat="server"
/>
<asp:Button ID="btn1"
runat="server" Text="test" />
</form>
WebUserControl.ascx
<%@ OutputCache Duration="3600"
VaryByParam="MenuID" %>
<%=Request.QueryString("MenuID")%>
The Solution:
Simply add a hidden field
to your page like so:
<input type="hidden"
name="MenuID" value="<%= If(Request.QueryString("MenuID")
isnot nothing, Request.QueryString("MenuID").ToString(), "")
%>" />
It works perfect and as expected, I used this in a project I
am working on and it has solved my headache :). Seems a bit
hackish but dont see another way....
Thanks
Stefan