Object Persistance Throughout Pages

vbFace

Freshman
Joined
Nov 17, 2003
Messages
31
Suppose I create a custom class object, and I want this object to persist throught the pages of an on-line survey. How would I go about ensuring this persistence? Can I instantiate the object in the global.aspx Sub Session_Start(Sender As Object, E As EventArgs)? Or, can I assign this custom object as a property of the Session Object?


i.e
Visual Basic:
Sub Session_Start(Sender As Object, E As EventArgs)
 
 Dim myCustObj as MyCustomClassObject

    Session("UserObject") = myCustObj

End Sub
 
Yes, assign it to the Session variable like you're currently doing.
Then, to access it from a page, just cast it to the correct type.

For example:

Visual Basic:
Dim myCustObj As MyCustomClassObject

myCustObj = DirectCast(Session("UserObject"), MyCustomClassObject)
' Here you manipulate myCustObj
 
To add to Bucky's post...

In case myCustObj does not contain all expected values during Session_start you can assign to it from any page using the same method.
Visual Basic:
Session("UserObject") = myCustObj
 
Very nice. Thanks guys.

Robby, do you mean that if I change the values in the object on a page, I have to re-assign the object to the Session object, so the new data in the object is available on the next page?
 
I'm looking for a similar solution, but have hit a snag.

I've created a custom Product class and compiled it. I can access it on the individual page using the following code:

Code:
<%
  Dim objProduct As Product
  objProduct = New Product()

  objProduct.ID = 123456
  objProduct.PartNumber = "Part Number 12345"
  objProduct.Description = "This is the description of the product"
  objProduct.Category = 1
  objProduct.QuantityPerUnit = 1
  objProduct.UnitSize = "each"
  objProduct.UnitSellPrice = 24.99

%>

However, when I try to declare a Product variable in my global.asax file as in your example:

Code:
    Sub Session_Start(Sender As Object, E As EventArgs)
        Dim objProduct As Product
        Session("objProduct") = objProduct
    End Sub

I get a error message saying "Compiler Error Message: BC30002: Type 'Product' is not defined." I know its not a problem with my Product class, since I can declare and manipulate it on other pages, but when I try to declare it in the session variable, it fails.

Any ideas?
 
The problem does not lie in the setting of the variable to a
Session variable; it lies in the declaration of objProduct. Make
sure that the page has the correct Imports statement to
import the namespace that Product is declared in.
 
Back
Top