In some cases, you may want to cache the ASP.net page, but you need to update the selected section on the page based on each request. For example, you might want to cache a large portion of a page, but you need to dynamically update the time-related information on the page.
You can use the substitution control to insert dynamic content into a cached page. The substitution control does not render any markup. You need to bind the control to a method on the page or on a parent user control. You want to create a static method on your own to return any information you want to insert into the page. The method invoked by the substitution control must conform to the following criteria:
This method is defined as a static method (shared method in Visual Basic).
This method accepts parameters of the HttpContext type.
This method returns a value of type String.
Note that the substitution control cannot access other controls on the page, that is, you cannot check or change the values of other controls. However, the code can indeed use the arguments passed to it to access the current page context.
When the page runs, the substitution control invokes the method and replaces the substitution control on the page with the return value from the method.
The following are two ways to demonstrate that the substitution control generates dynamic content on the cached page, the cache time is 20 seconds, and no matter how many times it is refreshed in 20 seconds, the direct output time is unchanged. The substitution control on the page calls the static method GetCurrentTime, and each invocation is variable.
Code one: Using the Response.Cache correlation method to set the cache
Copy Code code as follows:
<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>
Inserting dynamic content on cached pages--using the substitution control demo
<p>
Cache time:<%= DateTime.Now.ToString ()%>
</p>
<p>
<b>real time:<asp:substitution id= "Substitution1" runat= "Server" methodname= "GetCurrentTime"/>
</b>
</p>
</div>
Code two: Using the OutputCache command to set the cache
Copy Code code as follows:
<%@ OutputCache duration= "No" varybyparam= "None"%>
<script runat= "Server" >
static string GetCurrentTime (HttpContext context)
{
return DateTime.Now.ToString ();
}
</script>
<div>
Inserting dynamic content on cached pages--using the substitution control demo
<p>
Cache Time:
<%= DateTime.Now.ToString ()%>
</p>
<p>
<b>real time:<asp:substitution id= "Substitution1" runat= "Server" methodname= "GetCurrentTime"/>
</b>
</p>
</div>