如何在没有代码的情况下在自定义控件上设置输出缓存指令

时间:2020-03-05 18:57:40  来源:igfitidea点击:

我已经编写了一个继承自System.Web.UI.WebControls.DropDownList的控件,因此该控件的前面没有任何代码,但是我仍然想设置OutputCache指令。我有什么办法在Ccode中设置它,比如说带有属性或者类似的东西?

我特别希望能够复制VaryByParam属性

解决方案

回答

Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);

回答

我意识到这是一个令人难以置信的古老问题,但仍然值得回答。

我们所说的不是用户控件,而是自定义控件。我们想要使用OutputCache进行的操作可以简单地通过上下文缓存来完成。

在获取数据并绑定到DropDownList的代码中,执行以下操作:

List<Object> listOfObjects = null;
//assuming a List of Objects... it doesn't matter whatever type of data you use
        if (Context.Cache["MyDataCacheKey"] == null)
        {
            // data not cached, load it from database
            listOfObjects = GetDataFromDB();
//add your data to the context cache with a sliding expiration of 10 minutes.
            Context.Cache.Add("MyDataCacheKey", listOfObjects, null,
                System.Web.Caching.Cache.NoAbsoluteExpiration,
                TimeSpan.FromMinutes(10.0),
                System.Web.Caching.CacheItemPriority.Normal, null);
        }
        else
            listOfObjects = (List<Object>)Context.Cache["MyDataCacheKey"];

        DropDownList1.DataSource = listOfObjects;
        DropDownList1.DataBind();