Recipe 7.4. Preserving Information Between Postbacks


Problem

You have a page that needs to remember the state's value between postbacks to determine how to display the page.

Solution

Use the RegisterHiddenField method of the ClientScript object to create a hidden text field in the rendered page.

Nothing special is required in the .aspx file. Instead, in the code-behind class for the page, use the .NET language of your choice to:

  1. Programmatically insert a hidden text field into the form using the RegisterHiddenField method of the ClientScript object.

  2. Use this field to store the value of the state you wish to preserve between postbacks.

  3. Access the hidden text field on subsequent submissions of the page to the server.

Figure 7-3 shows the output of a form that preserves the page state using a hidden field. Clicking the Prev/Next buttons decrements/increments the value in the hidden field by one. Example 7-13 shows the .aspx file that produces the form. Examples 7-14 and 7-15 show the companion VB and C# code-behind files that demonstrate how to access the application state data.

Figure 7-3. Maintaining page state with a hidden field


Discussion

An approach we favor for remembering the current state of a value between postbacks to the server involves programmatically inserting one or more hidden text fields into a form.

A similar technique is commonly used by classic ASP developers, who explicitly place a hidden text field in the form and set its value in the page code. You can use the same technique in ASP.NET pages. However, ASP.NET, unlike classic ASP, lets you programmatically insert hidden text fields into a form at runtime. The significant advantage here is that all code you write is kept in the code-behind, allowing the .aspx file to contain only the presentation aspects (hidden fields contain no user interface).

One negative aspect of using hidden fields for storing state data is that the data is stored in plain text. If you do not want the data to be visible in the rendered HTML, you should store the data in the ViewState instead, as described in Recipe 7.4.

As an example of when you might use hidden fields, suppose your application supports complex sorting within a DataGrid, such as a two-way sort that involves ascending and descending columns and might even be supported by your own sorting expressions. You can use hidden fields to maintain information about how a user has performed a specific sort so you can preserve the user's sorting order and choice of sorted columns.

Our example that illustrates the solution is simple to focus on the concept of storing information in hidden fields each time a page is submitted to the server. The example programmatically inserts a single hidden field into a form and then increments or decrements its value based on the button clicked by the user.

Because the hidden field is accessed from many points in the code-behind, a constant at the class level, PAGE_STATE, defines the name of the hidden field that is programmatically inserted into the rendered page. This avoids hardcoding the hidden field name throughout the code and the associated maintenance issues.

In the Page_Load method, updatePage, which is the method used to update the page based on the page state, is called passing a value of 0 as the initial page state value.

In the updatePage method, a label is updated to indicate the current state value. After updating the page to reflect the current page state, the RegisterHiddenField method of the Page object is used to save the page state value in the rendered page.

The rendered page contains the following hidden form variable that can be retrieved when the page is submitted to the server. The name is set to the value of the PAGE_STATE constant, and the value is set to the current page state:

 <input type="hidden" name="PageState"  value="0" /> 

Hidden fields always store the value as a string. This requires any data saved using the technique to be converted to a string when the RegisterHiddenField method is called.


In this example, two buttons are provided to increment and decrement the page state, respectively. An event handler is added in the code-behind for each of the button click events. The event handler for the increment button is called btnNextState_Click; the event handler for the decrement button is btnPrevState_Click. In the event handlers, the current page state is retrieved from the hidden field, adjusted as required, and then the updatePage method is called to update the page and save the new page state value in the form when the page is rendered.

The example demonstrates how easy ASP.NET has made it to persist information needed for each round trip between the server and the client. For an example of persisting more complex data between page submittals, refer to Recipe 7.4.

See Also

Recipe 7.4

Example 7-13. Maintaining page state with hidden values (.aspx)

 <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH07HiddenValuesVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH07HiddenValuesVB" Title="Hidden Values" %> <asp:Content  runat="server" ContentPlaceHolder> <div align="center" > Maintaining Page State With Hidden Fields (VB) </div> <table width="30%" align="center"  runat="server"> <tr > <td>Current Page State: </td> <td><asp:Label  Runat="server" /></td> </tr> <tr> <td colspan="2" align="center"> <br /> <asp:Button  runat="server"    Text="Prev State"    OnClick="btnPrevState_Click" /> <asp:Button  runat="server"    Text="Next State"    OnClick="btnNextState_Click" /> </td> </tr> </table> </asp:Content> 

Example 7-14. Maintaining page state with hidden values code-behind (.vb)

 Option Explicit On Option Strict On Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH07HiddenValuesVB.aspx ''' </summary> Partial Class CH07HiddenValuesVB Inherits System.Web.UI.Page 'The following variable defines the name of the hidden field in the 'form used to track the page state Private PAGE_STATE As String = "PageState" '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the page load event. It ''' is responsible for initializing the controls on the page. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Private Sub Page_Load(ByVal sender As Object, _   ByVal e As System.EventArgs) Handles Me.Load If (Not Page.IsPostBack()) Then 'not a postback so initialize the page state to 0 updatePage(0) End If End Sub 'Page_Load '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the next state button ''' click event. It is responsible for setting the page state ahead ''' one state. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnNextState_Click(ByVal sender As Object, _  ByVal e As System.EventArgs) Dim pageState As Integer pageState = CInt(Request.Form(PAGE_STATE)) pageState += 1 updatePage(pageState) End Sub 'btnNextState_Click '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the previous state button ''' click event. It is responsible for setting the page state back one ''' state. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnPrevState_Click(ByVal sender As Object, _  ByVal e As System.EventArgs) Dim pageState As Integer pageState = CInt(Request.Form(PAGE_STATE)) pageState -= 1 updatePage(pageState) End Sub 'btnPrevState_Click '''*********************************************************************** ''' <summary> ''' This routine updates the page for the passed page state. ''' </summary> ''' ''' <param name="pageState">Set to the current page state</param> Private Sub updatePage(ByVal pageState As Integer) 'update the current page state display labPageState.Text = pageState.ToString() 'register the hidden field used to persist the current page state ClientScript.RegisterHiddenField(PAGE_STATE, _  pageState.ToString()) End Sub 'updatePage End Class 'CH07HiddenValuesVB End Namespace 

Example 7-15. Maintaining page state with hidden values code-behind (.cs)

 using System; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH07HiddenValuesCS.aspx /// </summary> public partial class CH07HiddenValuesCS : System.Web.UI.Page { // The following variable defines the name of the hidden field in the // form used to track the page state private String PAGE_STATE = "PageState"; ///*********************************************************************** /// <summary> /// This routine provides the event handler for the page load event. /// It is responsible for initializing the controls on the page. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { // not a postback so initialize the page state to 0 updatePage(0); } } // Page_Load ///*********************************************************************** /// <summary> /// This routine provides the event handler for the next state button /// click event. It is responsible for setting the page state ahead /// one state. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnNextState_Click(object sender, EventArgs e) { int pageState; pageState = Convert.ToInt32(Request.Form[PAGE_STATE]); pageState += 1; updatePage(pageState); } // btnNextState_Click ///*********************************************************************** /// <summary> /// This routine provides the event handler for the previous state button /// click event. It is responsible for setting the page state back one /// state. /// </summary> /// /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnPrevState_Click(object sender, EventArgs e) { int pageState; pageState = Convert.ToInt32(Request.Form[PAGE_STATE]); pageState -= 1; updatePage(pageState); } // btnPrevState_Click ///*********************************************************************** /// <summary> /// This routine updates the page for the passed page state. /// </summary> /// /// <param name="pageState">Set to the current page state</param> private void updatePage(int pageState) { // update the current page state display labPageState.Text = pageState.ToString(); // register the hidden field used to persist the current page state ClientScript.RegisterHiddenField(PAGE_STATE,  pageState.ToString()); } // updatePage } // CH07HiddenValuesCS } 



ASP. NET Cookbook
ASP.Net 2.0 Cookbook (Cookbooks (OReilly))
ISBN: 0596100647
EAN: 2147483647
Year: 2003
Pages: 202

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net