Saturday, March 31, 2012

Storing/Retrieving Objects in the Session

I have a form set up currently so that when someone is added, an object is created with that persons information, and that object is then added to the Session. When the user is done with the form, I have the code setup to mirror the information back on a webpage (when I know it's spewing back the same information I put in, then I'll have it be stored in a database). The problem I am having is that I don't know how to call my toString method of my object from the session.
The class is called Person, and the object is called objPerson, I store it this way:

Session.Add("objPerson", objPerson)

and echo it back to the screen this way:

Response.Write(Session.Item("objPerson"))

The only thing that comes out is the name of the object though, with the namespaces ( COCO.objects.Person ). I tried using

Response.Write( Session.Item( "objPerson.toString()") )

But I had a feeling that wouldn't work, and it didn't. Have I approached this wrong, or am I on the right track here?
Thanks,
DSimmonHi there...

The problem is that you have to sat your item from the session to the Object type of that item, and then you can use it.

Assuming that the class of objPerson is "Person", you would have to do something like this to retreive it:

Person sessionPerson = (Person)Session("Person");

And then use 'sessionPerson' as you want to.

You can use it directly also like this:

((Person)Session("Person")).Name;

Again, assuming you have a "Name" for your "Person" class.

I hope this helps, let me know if you need more info.

Covo
Ahh, so I have to make a storage when I retrieve the object from the session, then recast it to that object type before I use it.
That makes sense, I'll try it now.
Thanks for you help.

David
you're welcome!

Notice that you don't have to make a storage object... If you see the second method I listed, you'll see that you can just cast the session to the object and use it directly.

0 comments:

Post a Comment