在《ASP.NET2.0揭秘读书笔记之八——页面输出缓存 》文章中,谈了如何缓存页面的全部输出,在我们只需要缓存页面的一部分内容时,而另外一部分内容需要动态更新时,这个时候我们可以用部分页面缓存技术。
启用部分页面缓存的方法主要有两种:
(1) 缓存后替换技术(post-cache substitution)
(2) 使用用户控件来缓存页面中一个特定区域,而不是整个页面。
可以以声明方式或者编程的方式来使用缓存后替换技术(这个名字取得不咋样)。如果希望以声明方式来使用缓存后替换,则要使用ASP.NET的Substitution控件。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
<%@ Page Language="C#" %>
<%@ OutputCache Duration="15" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
public static string GetTime(HttpContext context)
{
return DateTime.Now.ToString("T");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Substitution Control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
The cached time is: <%= DateTime.Now.ToString("T") %>
<hr />
The substitution time is:
<asp:Substitution
id="Substitution1"
MethodName="GetTime"
Runat="server" />
</div>
</form>
</body>
</html>
Substitution控件有一个重要的属性:MethodName。MethodName属性接受页面上定义的一个方法的名称,该方法必须是静态的,因为当页面输出缓存时,页面实例还没有被创建。
可以像ASP.NET 页面一样在内存中缓存用户控件呈现的内容。当给用户控件添加%@OutputCache%指令时,用户控件的输出内容就被缓存了。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
Code
<%@ Control Language="C#" ClassName="Movies" %>
<%@ OutputCache Duration="600" VaryByParam="none" %>
User Control Time:
<%= DateTime.Now.ToString("T") %>
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
Runat="server" />
<asp:SqlDataSource
id="srcMovies"
ConnectionString="<%$ ConnectionStrings:Movies %>"
SelectCommand="SELECT Title,Director FROM Movies"
Runat="server" />