使用 Substitution 控制項指定輸出緩衝網頁上要以動態內容替換該控制項的部分。Substitution 控制項為要緩衝大部分內容的頁提供了一種緩衝局部頁的簡化解決方案。可以對整頁進行輸出緩衝,然後使用 Substitution 控制項指定頁中免於緩衝的部分。需要緩衝的地區只執行一次,然後從緩衝讀取,直至該快取項目到期或被清除。動態地區則在每次請求頁時執行。由於不必對這些部分進行封裝以緩衝在 Web 使用者控制項中,因此,此緩衝模型簡化了主要是靜態內容的頁的代碼。例如,如果頁包含靜態內容(如新聞報道)和顯示廣告的 AdRotator 控制項,這種情況下,此緩衝模型就很有用。新聞報道不會更改,這意味著它們可以緩衝。但是,您希望在使用者每次請求該頁時都顯示一條新廣告。AdRotator 控制項直接支援緩衝後替換,無論頁是否緩衝,都在該頁回傳時呈現一個新廣告。
注意 |
在快取頁面包含的使用者控制項中可以放置 Substitution 控制項。但是,在輸出緩衝使用者控制項中不能放置 Substitution 控制項。 |
Substitution 控制項執行時,會調用一個返回字串的方法。該方法返回的字串即為要在頁中的 Substitution 控制項的位置上顯示的內容。使用 MethodName 屬性指定要在 Substitution 控制項執行時調用的回調方法的名稱。指定的回調方法必須是包含 Substitution 控制項的頁或使用者控制項的靜態方法。回調方法的簽名必須與接受 參數並返回字串的 委託的簽名匹配。
若要操作頁的輸出緩衝,可使用 指令、 類或 屬性。有關快取頁面的更多資訊,請參見 和。
Substitution 控制項的另一種使用方法是,使用 HttpResponseSubstitutionCallback 委託實現緩衝替換行為。此外,還可以在直接支援緩衝替換功能的控制項(如 AdRotator 控制項)上實現緩衝替換行為。有關更多資訊,請參見。
樣本:
<%@ outputcache duration="60" varybyparam="none" %><script runat="server" language="C#">void Page_Load(object sender, System.EventArgs e){// Display the current date and time in the label.// Output caching applies to this section of the page.CachedDateLabel.Text = DateTime.Now.ToString();}// The Substitution control calls this method to retrieve// the current date and time. This section of the page// is exempt from output caching.public static string GetCurrentDateTime (HttpContext context){return DateTime.Now.ToString ();}</script><html><head runat="server"><title>Substitution Class Example</title></head><body><form runat="server"><h3>Substitution Class Example</h3><p>This section of the page is not cached:</p><asp:substitution id="Substitution1"methodname="GetCurrentDateTime"runat="Server"></asp:substitution><br /><p>This section of the page is cached:</p><asp:label id="CachedDateLabel"runat="Server"></asp:label><br /><br /><asp:button id="RefreshButton"text="Refresh Page"runat="Server"></asp:button></form></body></html>