views:

605

answers:

2

I've written a control that inherits from the System.Web.UI.WebControls.DropDownList and so I don't have any code in front for this control, but I still want to set the OutputCache directive. I there any way to set this in the C# code, say with an attribute or something like that?

I'm particularly hoping to be able to replicate the VaryByParam property

A: 
Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
Response.Cache.SetCacheability(HttpCacheability.Server);
Response.Cache.SetValidUntilExpires(true);
dimarzionist
The response object isn't a property of the control, only of the parent Page, so wouldn't this only change the cache settings for the whole page?
Glenn Slaven
+2  A: 

I realize this is an incredibly old question but it is still worthy of an answer.

What you are talking about isn't a User Control it is a Custom Control. What you want to do with the OutputCache can be done simply with the Context Cache.

In your code where you are getting the data and binding to your DropDownList do something like this:

        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();
matt-dot-net
Thankyou very much!
Glenn Slaven