[转]ASP.NET 缓存(十三)--通过使用声明性的属性缓存用户控件的多个版本

只需在 .aspx 文件中多次声明某个用户控件便可以缓存该用户控件的多个版本。如同没有进行输出缓存的用户控件一样,您可以根据应用程序的需要将一个用户控件多次包含在 ASP.NET 页。控件输出的多个版本都会存储在缓存中,除非您将用户控件的 Shared 属性设置为真。

通过使用声明性的属性缓存用户控件的多个版本

  1. 在 .ascx 文件中使用 @ OutputCache 指令或在代码隐藏类中使用 PartialCachingAttribute 属性,指定用户控件的输出缓存设置。
  2. 在页中包括用户控件的多个版本,将在类中定义的属性作为属性包括在元素中。确保属性值在页上是唯一的。

当为根据分配给该属性的值自定义用户控件输出的用户控件定义属性,这种技术很有用。以下示例说明了这一点。如果将以下内容用作包含用户控件的 .aspx 页,可以在用户控件声明中使用 State 属性以生成用户控件的不同版本,一个版本用于 CA,一个版本用于 UT

<%@ Register TagPrefix="MyControl" TagName="StateSort" Src="fragcache.ascx" %>
<form runat="server" >
<p>This page was generated at <%=DateTime.Now%>.
<br>
<MyControl:StateSort State="CA" runat="server" />
<br>
<MyControl:StateSort State="UT" runat="server" />
</form>

用户控件 fragcache.ascx 包含 State 属性,该属性使您能够将属性包含在页的用户控件服务器标记中。

[C#]
<%@ OutputCache Duration="120" VaryByParam="None" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat=server>
public String State;
void Page_Load(Object sender, EventArgs e)  {
String selectCmd = "select * from Authors where state = @State";
SqlConnection myConnection = new SqlConnection("server=(local)\\NetSDK;database=pubs;Trusted_Connection=yes");
SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection);
myCommand.SelectCommand.Parameters.Add(new SqlParameter("@State", SqlDbType.NVarChar, 2));
myCommand.SelectCommand.Parameters["@State"].Value = State;
DataSet ds = new DataSet();
myCommand.Fill(ds, "Authors");
MyDataGrid.DataSource= ds.Tables["Authors"].DefaultView;
MyDataGrid.DataBind();
}
</script>
<asp:datagrid id="MyDataGrid" runat="server" />
<br>
<p>This control was generated at <% =DateTime.Now %>.
[Visual Basic]
<%@ OutputCache Duration="120" VaryByParam="None" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="VB" runat="server">
Public State As String
Sub Page_Load(sender As Object, e As EventArgs)
Dim selectCmd As String = "select * from Authors where state = @State"
Dim myConnection As New SqlConnection("server=(local)\NetSDK;database=pubs;Trusted_Connection=yes")
Dim myCommand As New SqlDataAdapter(selectCmd, myConnection)
myCommand.SelectCommand.Parameters.Add(New SqlParameter("@State", SqlDbType.NVarChar, 2))
myCommand.SelectCommand.Parameters("@State").Value = State
Dim ds As New DataSet()
myCommand.Fill(ds, "Authors")
MyDataGrid.DataSource = ds.Tables("Authors").DefaultView
MyDataGrid.DataBind()
End Sub 'Page_Load
</script>
<asp:datagrid id="MyDataGrid" runat=server/>
<br>
<p>This control was generated at <% =DateTime.Now %>.

只是将带有有效持续时间值的 @ OutputCache 指令包括在 .ascx 文件中便可以实现该用户控件改变的缓存输出。

posted @ 2007-01-30 16:38  么么茶.NET  阅读(325)  评论(0编辑  收藏  举报