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
 

2 Comments

  • What about the VaryByControl option in controls. It is needed for postbacks.

  • Hello,

    I tried to use varybycontrol but this still did not give me the results expected. I was under the impression that vary by control was for when you wanted to vary the output by the contents of a control, i.e. a dropdown in your control and you would like to vary for each value in the dropdown.

    Can you give an example of how this could solve my issue? The way I have it atm seems to work fine. But I have not found anyone that has the issues I do yet so it is possible I am doing something wrong.


    Thanks
    Stefan

Comments have been disabled for this content.