Question

If I create an object in the code-behind of an .aspx page, how long can I expect that object to live? Will it live across post-backs? Could I pass it somehow to another page? Could I make it live as long as, say, the session object?

I searched the web hoping for a document explaining the life-cycle of objects created from the code-behind, and how to interact with this life-cycle; any related links would be appreciated.

By the way, I am using C# in the code-behind, but I imagine most advice targeting VB would be applicable as well.

Was it helpful?

Solution

The code-behind lives for the duration of the request. It will not live across post-backs. You can add values to Session if you want it across a postback. The same would apply to VB.

OTHER TIPS

If I create an object in the code-behind of an .aspx page, how long can I expect that object to live? Will it live across post-backs? Could I pass it somehow to another page? Could I make it live as long as, say, the session object?

You can save object instances within the session:

Session["Foo"] = new MyFoo();

You can retrieve the instance on any page that has access to the session:

MyFoo foo = (MyFoo) Session["Foo"];

An alternative to this is using a static variable - in this case the variable keeps its value until the app domain gets destroyed (i.e. when IIS is restarted) - but it is also global in the sense that it has the same value for all users (since its not related to the session at all).

The object will only live as long as the page, i.e. for the duration of the page request. If you want to make it live longer you can store in the Session and retrieve it for each request.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top