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

</script>

<html>

<body>

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

<h3>

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

<tr>

<td>

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

<td>

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

<td>

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

<td>

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

<td>

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

<td>

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

<td>

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

<td>

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

</tr>

</table>

<p>

</p>

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

<SelectParameters>

<asp:QueryStringParameter Name="state" QueryStringField="state" DefaultValue="CA" />

</SelectParameters>

</asp:SqlDataSource>

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

<p>

<i>Last generated on:</i>

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

</p>

</form>

</body>

</html>

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