Imran Rizvi
Imran Rizvi

Reputation: 7438

How to cache a User Control for one day

I have a user control that draws a table

I have another user control that draws images

I want to cache both the user control for one day , it means for everyday if a user visits table and images will be generated only for first time and saved to cache and used whole day from cache for any subsequent visit.

This cache should be depended on three keys including logged in user key

I have written custom code for images and it is working fine, I am storing these images to a folder. this is without using output caching.

Now I don't have any idea how to store Table to a folder, so I want to implement caching for table using Output Caching of user control.

I don't know how to cache it for one day.

As instructed by Rick I added the following directive to user control

<%@ OutputCache Duration="86400" VaryByParam="None" Shared="true"
    VaryByControl="Key1;Key2;Key3" %>

And wrote the following code to consumer page

DashboardControl dc = null;
Control control = (Control)Page.LoadControl(urlBuilder.GetCompleteURL().TrimEnd('?'));
  if (control is DashboardControl)
  {
    dc = control as DashboardControl;
  }
  else if (control is PartialCachingControl && ((PartialCachingControl)control).CachedControl != null)
  {
    dc = (DashboardControl)((PartialCachingControl)control).CachedControl;
  }

But CachedControl always give null , any idea?

Upvotes: 0

Views: 2570

Answers (3)

Nethol
Nethol

Reputation: 1

It always gives null if the control (PartialCachingControl) is not added to the page, after you added of some way to the page and render the control, it will give you access via CachedControl property.

Upvotes: 0

RickNZ
RickNZ

Reputation: 18654

Try this:

  <%@ OutputCache Duration="86400" VaryByParam="None" Shared="true"
      VaryByControl="Key1;Key2;Key3" %>

Where Key1, Key2 and Key3 are a properties on the control whose value is used to vary the cache.

When a Control is output cached, only its output is placed in the cache, not the Control itself. On subsequent requests where the output cache is used, references to the Control will be null, so you need to set properties on the Control the first time it's referenced.

For a cached Control, LoadControl() will return a PartialCachingControl type, which you can use to add the result to your Page. But the Control class itself is not there, so you can't use that reference to set property values or invoke methods.

Upvotes: 2

Manisha Awasthi
Manisha Awasthi

Reputation: 479

Try using following code example for caching user control . Here you have to change the duration as per your requirement and User control name as per your control:

    <%@ OutputCache Duration="60" VaryByParam="none" 
    VaryByControl="CategoryDropDownList" %>

For more refer link : http://msdn.microsoft.com/en-us/library/aa478965.aspx

Upvotes: 2

Related Questions