Need basic help with classes

C

CarlosSanchezJr

I have a User class that for example's sake looks something like this:

public class User
{
private int userId;
private string userName;
private string FirstName;
private string LastName;

public int UserId
{
get { return userId; }
set { userId = value; }
}
public int UserName
{
get { return userName; }
set { userName = value; }
}
public int FirstName
{
get { return firstName; }
set { firstName = value; }
}
public int LastName
{
get { return lastName; }
set { lastName = value; }
}
}

Now I understand if I want to create an instance of this on a code
behind page, I would do the following:

User user = new User();
user.UserId = 2;
etc....

What I want to know is, once I populate User with data, can I access
that data from a completely different page (than the one which
populated it or created the new instance)? Any help would be greatly
appreciated.
 
L

Laurent Bugnion

Hi,

I have a User class that for example's sake looks something like this:

public class User
{
}

Now I understand if I want to create an instance of this on a code
behind page, I would do the following:

User user = new User();
user.UserId = 2;
etc....

What I want to know is, once I populate User with data, can I access
that data from a completely different page (than the one which
populated it or created the new instance)? Any help would be greatly
appreciated.

The Page object is created on every request, and deleted every time that
the request is completed. It means that the objects belonging to the
Page must be recreated every time. That's the "stateless" approach.

However, you can save objects between roundtrips and share them between
pages by saving them in the Session. Each Page has a Session property,
which is created when the first request arrives, and which is deleted
only when the session is explicitly terminated, or when the session
timeout occurs (typically 20 minutes after the last request was processed).

To save an instance like you create in the session object, from within
the Page, you simply do

this.Session[ "aLabel" ] = user;

When you retrieve the object, you must cast it:

User user = (User) this.Session[ "aLabel" ];

If this is the first call, then the object will be null.

There are other strategies to persist objects between requests, but this
is probably the most standard one.

HTH,
Laurent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top