Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On page reload, all objects are destroyed?

How can I make a persistent list of objects X that survives page reload / post-back in c# / asp.net ? This was never a problem in c#, but in asp.net, a post-back will wipe out everything.

like image 362
Half_Baked Avatar asked Jan 24 '26 03:01

Half_Baked


2 Answers

Asp.net is built for HTTP protocol which is stateless, so you can not find the object on post back. You can use view state instead.

ViewState

Microsoft® ASP.NET view state, in a nutshell, is the technique used by an ASP.NET Web page to persist changes to the state of a Web Form across postbacks.

The Role of View State

View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.

like image 94
Adil Avatar answered Jan 26 '26 18:01

Adil


You can always save your items to the current Session.

For example:

Session["var1"] = // whatever you want

And your Session object will exist until the current session expires regardless of PostBacks.

like image 22
Mike Marks Avatar answered Jan 26 '26 18:01

Mike Marks