Subscribe

RSS Feed (xml)

Partial Page Output Caching Using VaryByControl

The


VaryByControl directive provides a helpful shortcut to vary the User Controls output


by a contained control.


<%@ Imports Namespace="System.Data.SqlClient" %>


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


<script runat="server">


Sub Page_Load (sender As object, e As EventArgs)


Dim connection As New SqlConnection([your connection string])


Dim command As New SqlCommand("BookSelection", connection)


' Mark as a stored procedure


command.CommandType = CommandType.StoredProcedure


' Set up a SQL parameter for the book type selected


command.Parameters.Add("@BookType",


SqlDbType.NVarChar, 25).Value =


SortBy.SelectedItem.Value


' Execute


connection.Open()


BookListing.DataSource = command.ExecuteReader()


BookListing.DataBind()


connection.Close()


End Sub


</script>


<form runat="server">


Please select the types of books you are interested in:


<asp:DropDownList AutoPostBack="true" id="SortBy" runat="server" >


<asp:listitem >Technology</asp:listitem>


<asp:listitem >Fiction</asp:listitem>


<asp:listitem >Non-Fiction</asp:listitem>


</asp:DropDownList>


<br>


<asp:DataGrid runat="server" id="BookListing" />


</form>


Comments


Consider a User Control that displays a list of the top 10 books with a SortBy


DropDownList containing Technology, Fiction, and Non-Fiction.Whenever a user


changes a value in the DropDownList the server returns data filtered by the value of


SortBy.



The content generated by the User Control can be varied just as you can vary page


output cached responses. However, within a User Control, the name of the control,


SortBy, is namespaced to the name of the containing control-UserControl1:SortyBy.


This allows multiple Top10 User Controls to be hosted in the same page without experiencing


naming collisions.


For example, if you had two of these User Controls on your page, they might have


the IDs Top10Books1 and Top10Books2. Top10Books1:SortBy and Top10Books2:


SortBy are treated as separate drop-down controls.The VaryByControl option simply


allows you to avoid typing VaryByParam="Top10Books2:SortBy"-instead simply type


VaryByControl="SortBy".

No comments:

Archives

Variety in the Web World