Welcome to AspAdvice Sign in | Join | Help

ASP.NET: clear user control output cache

As per the subject, here's a simple sample

global.asax
 
<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        HttpRuntime.Cache.Insert("myCacheKey", DateTime.Now);

    }
          
</script>

 
Webusercontrol.ascx

<%@ Control Language="C#" ClassName="WebUserControl" %>
<%@ OutputCache VaryByParam="None" Duration="600"   %>
<script runat="server">
   
    protected void Page_Load(object sender, EventArgs e)
    {
        String[] dependencyKey = new String[1];
        dependencyKey[0] = "myCacheKey";

        BasePartialCachingControl pcc = Parent as BasePartialCachingControl;
        if(pcc != null)
         pcc.Dependency = new CacheDependency(null, dependencyKey);

    }
</script>
FROM UC:<%=DateTime.Now.ToString()%>

 
Default.aspx
<%@ Page Language="C#" %>

<%@ Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

    protected void Button2_Click(object sender, EventArgs e)
    {
        Cache.Insert("myCacheKey", DateTime.Now);
       
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <uc1:WebUserControl id="WebUserControl1" runat="server"></uc1:WebUserControl></div>
        FROM PAGE:<%=DateTime.Now.ToString() %>
        <asp:Button ID="Button1" runat="server" Text="Cause a postback" />
        <asp:Button ID="Button2" runat="server" Text="Remove from cache" OnClick="Button2_Click" />
    </form>
</body>
</html>

See also Steve Smith's article: Remove ASP.NET Page Output Cache Entries

Sponsor
Published Wednesday, October 31, 2007 1:06 AM by joteke
Filed under: ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
required 
(required) 
Enter the code you see below