Objects not maintaining values

  • Thread starter Thread starter MattC
  • Start date Start date
M

MattC

I have created a container class and instantiated it in one of my pages. I
fill the object on page load when not on a postback. On a button click i
want to do somethign with the values in that object, but on my button event
being reached the object is now empty.

private Visitor VisitorObj = new Visitor();
protected Label label1;

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
VisitorObj.GetVisitorDetails(); //loads object here
}
}

private void UpdateButton_Click(object sender, System.EventArgs e)
{
label1.Text = VisitorObj.VisitorID; //object is now empty though!!!
}

Any idea why the values in this object aren't being maintained across
postback but contents of the form on the page is.

MattC
 
You need to save your object between server round trips, possibly in the
Session object. The content of the controls on your Web form are by default
saved using view state.
 
Carsten,

Thanks for your reply.

Oddly though I have a Database class that wraps up some of the functionality
of ADO.NET and that maintains details such as then connection string set in
the SqlConnection object. This database class is stored within my Visitor
Object.

I thought that as my Visitor object was created at the server side once its
values are set they would remain set through round-trips. Or am i
misunderstanding ASP.NET a bit here :S

thanx

MattC
 
I thought that as my Visitor object was created at the server side once
its
values are set they would remain set through round-trips. Or am i
misunderstanding ASP.NET a bit here :S

Hi Matt,

ASP.Net works in an HTTP environment. This means that each browser request
takes place "in a vacuum" so to speak. There is no link between one browser
Request and another as far as the web server is concerned. An HTTP Request
is received, handled, and then forgotten. This is why ASP.Net leverages such
objects as Session, which puts a cookie on the client, so that the browser
"identifies" itself with each new Request (or PostBack), and the Server
Session memory that belongs to that browser instance can be re-assigned to
that Request. ViewState is another mechanism for helping the server to
"remember" information from the last Request, by storing the values of
various Server Controls in a hidden form field in the client HTML. The form
posts the hidden field back to the server, which can then rebuild objects
based upon the values posted back.

In other words, with each Page Request, all server-side objects in that Page
must be re-built from scratch, and populated with any old/new information
sent from the browser with the Request.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
Back
Top