7.3. Preserving Information Between Postbacks


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


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.

Maintaining page state with a hidden field

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


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

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.