ViewState v Session - Confused

  • Thread starter Thread starter mosscliffe
  • Start date Start date
M

mosscliffe

I am testing for how/when a page is posted back and I decided to use a
ViewState variable in PageLoad to set up a counter, but it appears,
the ViewState is cleared on each PageLoad. So then I used SESSION and
that worked.

Am I correct in assuming ViewState is cleared on each PageLoad or is my
code incorrect.

VIEWSTATE
If IsNothing(ViewState("PbCounter")) Then

ViewState("PBCounter") = 1
Else
ViewState("PBCounter") = Session("PBCounter") + 1
End If

SESSION
If IsNothing(Session("PbCounter")) Then

Session("PBCounter") = 1
Else
Session("PBCounter") = Session("PBCounter") + 1
End If

Response.write(ViewState("PBCounter").tostring) ALWAYS ONE

Response.write(Session("PBCounter").tostring) INCREMENTS CORRECTLY

Thanks - Richard
 
If this is really your code, then you are putting an empty Session
variable into the Viewstate.

VIEWSTATE
If IsNothing(ViewState("PbCounter")) Then
ViewState("PBCounter") = 1
Else
ViewState("PBCounter") = Session("PBCounter") + 1 <<<<<<<
HERE
End If
 
Sorry Typo - with cut and paste, no it was correct in the actual code.
I did viewstate first and when it did not work I then changed it to
session.
 
ViewState is stored in a Page, and passed back and forth to the client via a
hidden form field. Session is stored in Server memory. Therefore, ViewState
is scoped to a Page, but only to the Page after PostBack, not when it is
initially loaded. Session State is scoped to a single user Session, and
transcends Pages.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 
Eh?

On first page request you should be able to add custom values.
On postback you should be able to obtain it again.
Am i missing something here, i believe i thave tested this a while ago.
Of course a viewstate is bounded to a page but that could be welcome.
+ when using a master page you could tag stuff to multiple 'pages' (imo)
 
Yes, you can add values to it initially, but it is not stored. It is stored
in a hidden form field, which, when the page Posts Back, re-creates the
ViewState object from the field contents. In other words, if you add
something to a Page's ViewState, and navigate back to the same Page by any
means other then a PostBack, the ViewState will be empty.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Numbskull

Hard work is a medication for which
there is no placebo.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top