Sunday, November 18, 2007

ASP.NET 2.0 Caching (3) Fragment Caching




<%@ Control Language="VB" ClassName="FragCtrlwithAPI" %>

<%@ OutputCache Duration="60" VaryByControl="pickstate" %>

<script runat="server">

Private duration As TimeSpan

Sub Page_Load(ByVal sender As Object, ByVal E As EventArgs)

If (pickstate.SelectedValue = "CA") Then

duration = New TimeSpan(0, 0, 10)

CachePolicy.Duration = duration

End If

End Sub

Sub Page_PreRender(ByVal sender As Object, ByVal e As EventArgs)

Label1.Text = Now.ToString("G")

Label2.Text = Now.Add(CachePolicy.Duration).ToString("G")

End Sub

</script>

<div style="border: dotted 1px blue; padding: 5px; background-color: #eeeeee;">

<asp:DropDownList ID="pickstate" runat="server" AutoPostBack=true>

<asp:ListItem Text="CA" Value="CA" />

<asp:ListItem Text="UT" Value="UT" />

<asp:ListItem Text="MD" Value="MD" />

<asp:ListItem Text="OR" Value="OR" />

<asp:ListItem Text="MI" Value="MI" />

<asp:ListItem Text="TN" Value="TN" />

</asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:pubsConnectionString %>"

SelectCommand="SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] where state=@state"

ProviderName="System.Data.SqlClient">

<SelectParameters>

<asp:ControlParameter ControlID="pickstate" DefaultValue="CA" Name="state" PropertyName="SelectedValue" />

</SelectParameters>

</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" DataSourceID="sqldatasource1" />

<p>

Control cache starts at <asp:Label ID="Label1" runat="server" Text="Label"/><br />

Control cache expires at <asp:Label ID="Label2" runat="server" Text="Label"/><br />

</p>

</div>



<%@ Page Language="VB" %>

<%@ Register Src="datactrlnew.ascx" TagName="FragCtrl" TagPrefix="acme" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<acme:FragCtrl ID="FragCtrl1" runat="server" />

Current Time:

<%=Now.ToString("G") %>

<asp:Button ID="Button2" runat="server" Text="Refresh" />

</div>

</form>

</body>

</html>

In this code, only the user control is cached, so only the user control will not reflect the changes when you click refresh.

blog comments powered by Disqus