Saving data between postbacks in the ViewState collection

Saving data between postbacks in the ViewState collection

In classic ASP, the only way to preserve information – for example, the value of a variable- – between consecutive client requests is by means of Session variables, cookies, or other awkward techniques, such as arguments on the query string or values in hidden fields.

ASP.NET gives you yet another method, in the form of the ViewState property of the Page object. (More precisely, this is a protected property that the Page class inherits from the Control class.) This property represents the contents of the __VIEWSTATE hidden field and works as a StateBag dictionary of key-value pairs. The following example uses the ViewState property to preserve the number of requests to the current page:

Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles _    MyBase.Load    ' Number of requests to this page posted so far.    Dim count As Integer    If Not Me.ViewState("count") Is Nothing Then        count = CInt(Me.ViewState("count")) + 1    End If    ' Store the value back in the ViewState dictionary.    Me.ViewState("count") = count    ' Display in a Label control.    lblCount.Text = count.ToStringEnd Sub

Keep in mind that this property works only if you left the EnableViewState property set to True.

See also  11 Effective Keyword Research Tools and Techniques

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist