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.

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several