6.3. Preserving Information Between Postbacks
Problem
You have a page with a state
whose value the page needs to remember
between postbacks
to determine how the page should
be displayed.
Solution
Use the RegisterHiddenField
method of
the Page
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:
Programmatically insert a hidden text field into the form using the
RegisterHiddenField
method of thePage
object.Use this field to store the value of the state you wish to preserve between
postbacks
.Access the hidden text field on subsequent submissions of the page to the server.
Figure 6-3 shows the output of a simple 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 6-11 shows the .aspx
file that produces the form. Example 6-12
and Example 6-13 show the companion VB and C#
code-behind files that demonstrate how to access the application
state data.
Figure 6-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 ...
Get ASP.NET Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.