2

I need to access some variables in a page in web application. The scope of variables is just in that specific page. which one is the solution ? Session or ViewState ? or any better solution ?

 Private Property UserId() As Integer
            Get
                If Not ViewState("UserId") Is Nothing Then
                    Return CType(ViewState("UserId"), Integer)
                Else
                    Return -1
                End If

            End Get
            Set(ByVal Value As Integer)
                ViewState("UserId") = Value
            End Set
        End Property

or

Private Property UserId() As Integer
    Get
        If Not Session("UserId") Is Nothing Then
            Return CType(Session("UserId"), Integer)
        Else
            Return -1
        End If

    End Get
    Set(ByVal Value As Integer)
        Session("UserId") = Value
    End Set
End Property

And also Is ViewState custom per user?

2
  • 1
    Why do you need to do this, and do you need to do this from one request to the next? Commented Dec 7, 2010 at 2:20
  • 1
    Also, don't format your code that way. Leave off the ">", select the whole thing and press the "1/0/1" tool. Commented Dec 7, 2010 at 2:20

1 Answer 1

8

If you're going to be storing information that is unique to a user, across many pages, then Session is a good choice. A cookie is used to tie a user to a given Session, and Sessions will time out, which is something to keep in mind.

ViewState is simply a hidden field in HTML, so this can be used to persist objects when a page posts back to itself. The drawback is you're serializing your data into a string and sending it to the client (it's validated upon post back, so tampering with it will throw exceptions). To answer your question, yes, ViewState is per user per page.

If you need to store data that is accessed by all users of your site, Application storage or HttpContext.Cache are useful.

That's just a quick summary, for a more detailed description of your options, check out ASP.NET State Management Overview.

Sign up to request clarification or add additional context in comments.

1 Comment

I want to access the value of variables during the events of page. I don't wanna use public shared ones. I know about Session and View state and I don't need the variables across many pages.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.