在某些情況下,可能要緩存 ASP.NET 頁,但需根據每個請求更新頁上選定的部分。例如,您可能要緩存某頁的很大一部分,但需要動態更新該頁上的與時間高度相關的信息。
可以使用 Substitution 控件將動態內容插入到緩存頁中。Substitution 控件不會呈現任何標記。您需要將該控件綁定到頁上或父用戶控件上的方法中。您要自行創建靜態方法,以返回要插入到頁中的任何信息。由 Substitution 控件調用的方法必須符合下面的標準:
此方法被定義為靜態方法(在 Visual Basic 中為共享方法)。
此方法接受 HttpContext 類型的參數。
此方法返回 String 類型的值。
注意,Substitution 控件無法訪問頁上的其他控件,也就是說,您無法檢查或更改其他控件的值。但是,代碼確實可以使用傳遞給它的參數來訪問當前頁上下文。
在頁運行時,Substitution 控件會調用該方法,然后用從該方法的返回值替換頁上的 Substitution 控件。
下面分別用兩種方式演示 Substitution 控件在緩存頁上生成動態的內容,緩存時間為20秒,20秒內無論刷新多少次,直接輸出的時間都不變。而頁面上的 Substitution 控件調用靜態方法 getCurrentTime,每次調用都是變化的。
代碼一:使用Response.Cache相關方法設置緩存
復制代碼 代碼如下:
script runat="server">
static string getCurrentTime(HttpContext context)
{
return DateTime.Now.ToString();
}
void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.Now.AddSeconds(20));
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Cache.SetValidUntilExpires(true);
}
/script>
div>
h4>
在緩存頁面插入動態內容--使用substitution控件演示/h4>
p>
Cache Time:%= DateTime.Now.ToString() %>
/p>
p>
b>Real Time:asp:Substitution ID="Substitution1" runat="server" MethodName="getCurrentTime" />
/b>
/p>
/div>
代碼二:使用OutputCache命令設置緩存
復制代碼 代碼如下:
%@ OutputCache Duration="20" VaryByParam="none" %>
script runat="server">
static string getCurrentTime(HttpContext context)
{
return DateTime.Now.ToString();
}
/script>
div>
h4>
在緩存頁面插入動態內容--使用substitution控件演示/h4>
p>
Cache Time:
%= DateTime.Now.ToString() %>
/p>
p>
b>Real Time:asp:substitution id="Substitution1" runat="server" methodname="getCurrentTime" />
/b>
/p>
/div>
您可能感興趣的文章:- ASP.net Substitution 頁面緩存而部分不緩存的實現方法
- ASP.NET中Validation驗證控件正則表達式特殊符號的說明
- ASP.NET中CheckBoxList復選框列表控件詳細使用方法
- ASP.NET中DropDownList下拉框列表控件綁定數據的4種方法
- ASP.NET中FileUpload文件上傳控件應用實例
- ASP.NET中HiddenField隱藏域控件的使用方法
- ASP.NET中HyperLink超鏈接控件的使用方法
- ASP.NET中Image控件使用詳解
- ASP.NET中ImageButton圖片按鈕控件的使用
- ASP.NET 中 Button、LinkButton和ImageButton 三種控件的使用詳解