3

I want to apply output cache programmatically to a particular control. But when I'm using this code, it stores all the page and other user control in cache output.

    if (Session["id"] != null)
    {            
        Response.Cache.SetExpires(DateTime.Now.AddSeconds(60));
        Response.Cache.SetCacheability(HttpCacheability.Public);
        Response.Cache.SetValidUntilExpires(true); 
     }
Remko Jansen
  • 4,649
  • 4
  • 30
  • 39
pargan
  • 301
  • 3
  • 6
  • 19
  • Looks the same as this question: [Caching a user control in ASP.NET](http://stackoverflow.com/questions/568837/caching-a-user-control-in-asp-net) – Remko Jansen Mar 24 '12 at 11:00

1 Answers1

7

HttpResponse.Cache property gets caching policy (such as expiration time, privacy settings, and vary clauses) of a whole web page. That's why the code above caches the whole web page.

To cache your user control you could use PartialCachingAttribute. Is says that your control supports fragment caching. And then programmatically change the necessary caching properties through UserControl.CachePolicy property:

[PartialCaching(0)]
public partial class MyControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["id"] != null)
        {            
            this.CachePolicy.Duration = TimeSpan.FromSeconds(60);
        }
    }
}

Additional information could be found in the Caching Portions of an ASP.NET Page articke on MSDN.

Oleks
  • 31,955
  • 11
  • 77
  • 132
  • Alex is it cache store in clients side or server side. i want to store cache on client side. – pargan Mar 26 '12 at 08:36
  • @pargan, partial caching works only on the server side. Full caching can work either client and server side, or both. – Oleks Mar 26 '12 at 12:27
  • Alex but i want to maintain cache on client side of a particular user control with programmatically. can u please suggest me . how can i do this. ? – pargan Mar 26 '12 at 12:47
  • @pargan, I'm afraid this is impossible – Oleks Mar 26 '12 at 13:22