Vary by control properties using PartialCaching in ASP.NET

后端 未结 3 1911
别那么骄傲
别那么骄傲 2020-12-08 09:00

I am using the PartialCaching attribute on the base class of a user control.

I would like the cached controls to vary based on the properties set on the control inst

3条回答
  •  感情败类
    2020-12-08 09:17

    I'm posting a new answer to this very old question because the accepted answer is woefully inaccurate. This correct answer is:

    • There is no built-in way to vary by control property value. VaryByControl only works for controls.
    • When a cached version is served, your control field will be null. You can't change the cache duration in code - you would get a NullReferenceException.
    • There is a bug that varies cache by control ID and NamingContainer ID(s) if VaryByControl is set to any value. That is why it appears to work sometimes. The bug is right here: http://referencesource.microsoft.com/#System.Web/xsp/system/Web/UI/PartialCachingControl.cs#530

    I blogged about this recently right here: http://tabeokatech.blogspot.be/2014/09/outputcache-on-user-controls.html .

    A way you could make this work is call the builder method for the PartialCachingControl yourself in code-behind, and embed the property value you want to vary by in the guid parameter:

        // PhControls is an asp:PlaceHolder
        protected void Page_Init(object sender, EventArgs e)
        {
            for (int i = 0; i < 3; i++)
            {
                System.Web.UI.StaticPartialCachingControl.BuildCachedControl(PhControls, String.Format("Test{0}", i), String.Format("1234567{0}", i), 180, null, null, null, null, new System.Web.UI.BuildMethod(GetBuilderDelegate(i)), null);
            }
        }
    
        public Func GetBuilderDelegate(int number)
        {
            return delegate()
            {
                var control = (UserControls.Test)LoadControl("~/UserControls/Test.ascx");
                control.Number = number;
                return control;
            };
        }
    

    That neatly takes care of varying caching duration in code-behind as well. Make sure you remove the OutputCache directive from the markup in the ascx though when you do this. Otherwise the LoadControl gets you another PartialCachingControl and the cast fails.

提交回复
热议问题