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


<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: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"



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



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


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 />



<%@ Page Language="VB" %>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "">

<script runat="server">


<html xmlns="">

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

<title>Untitled Page</title>



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


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

Current Time:

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

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





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