Sunday, November 18, 2007

ASP.NET 2.0 Caching (1) VaryByPostBack

<%@ Page Language="VB" %>

<%@ OutputCache Duration="60" VaryByParam="state" %>

<script runat="server">

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

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

End Sub




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


<font face="Verdana">Using the Output Cache</font></h3>

<b>Authors by State:</b>

<table cellspacing="0" cellpadding="3" rules="all" style="background-color: #AAAADD;

border-color: black; border-color: black; width: 700px; border-collapse: collapse;">



<a href="varybypostback.aspx?state=CA">CA</a></td>


<a href="varybypostback.aspx?state=IN">IN</a></td>


<a href="varybypostback.aspx?state=KS">KS</a></td>


<a href="varybypostback.aspx?state=MD">MD</a></td>


<a href="varybypostback.aspx?state=MI">MI</a></td>


<a href="varybypostback.aspx?state=OR">OR</a></td>


<a href="varybypostback.aspx?state=TN">TN</a></td>


<a href="varybypostback.aspx?state=UT">UT</a></td>





<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:QueryStringParameter Name="state" QueryStringField="state" DefaultValue="CA" />



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


<i>Last generated on:</i>

<asp:Label ID="TimeMsg" runat="server" />





In this code, when you click the CA link, it will show 'Last generated on: 2007-11-18 10:23:35 ', when you click the IN link the next second, it will show 'Last generated on: 2007-11-18 10:23:36'. Now when you click CA link again, the time is still the same until after 60 seconds, it will refresh the data and the time. Same as all other links.

Two things to note:

1. if there is no caching, then say we have this page called VaryByPostBack.aspx, so if users all over the world are requesting it, the IIS will exexcute all the request and for each request IIS will send back a html to it.

2. if there is caching, for the first request, the IIS will produce a html, and cache it, then within the Duration, the page that all users all over the world requested will be the same html, the IIS is not producing a new html until after the duration.

blog comments powered by Disqus