星期三, 2月 25, 2009

動態控制usercontrol的cache

我們常常用cache來提昇網站的效率..不過也有時候需要用程式去控制cache..這裡來提供關於usercontrol的動態控制cache的作法..

作法一 : 控制權放在usercontrol裡..在usercontrol寫程式控制..

page.aspx

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:uc ID="uc1" runat="server" />
</div>
</form>
</body>
</html>

uc.cs

[PartialCaching(10)]
public partial class uc : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Text = DateTime.Now.ToString();

//這裡把Expires設成馬上過期..
BasePartialCachingControl pUc = Parent as BasePartialCachingControl;
if (pUc != null)
{
ControlCachePolicy ccp = pUc.CachePolicy;
ccp.SetExpires(DateTime.Now);
}
}
}

作法二 : 控制權放在page裡..動態load進usercontrol..

page.aspx


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>

page.cs

public partial class Default1 : System.Web.UI.Page
{
void Page_Init(object sender, EventArgs e)
{
//這裡把Expires設成馬上過期..
Control uc= this.LoadControl("~/uc.ascx");
PlaceHolder1.Controls.Add(uc);
PartialCachingControl pcc = uc as PartialCachingControl;
if (uc != null)
{
ControlCachePolicy ccp = pcc.CachePolicy;
ccp.SetExpires(DateTime.Now);
}
}
}

這兩種方法都可以做動態控制cache..有問題在互相討論ㄅ..Devil..

參考:

沒有留言: