0

I have an asp.net application where a user signs in at the login page. I create an Employee object and store the loginID on the button_click event of that page.

How would I keep the Employee object alive throughout the application (without having to pass the Employee object as a parameter everytime) ?

DNR
  • 3,706
  • 14
  • 56
  • 91

3 Answers3

4

This tends to be what Session State is for, storing session-scoped items.

Storing the employee object beyond a session would likely mean that the user that the object relates to is actually no longer using your site, therefore making it potentially pointless to keep the object in memory.

If you really do want it for the entire application, then Application State might be worth looking at.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
2

You probably want to take a look into using Session data.

It's an easy way to get an object associated and persisted with a given session, but there are caveats (it can have a performance impact depending on what your data store is, how large/complex the object you're persisting is and how many concurrent users you're dealing with).

48klocs
  • 6,073
  • 3
  • 27
  • 34
1

Given the class is:

[Serializable]
public class Employee
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Save it to session:

    protected void DoLogin()
    {

        Employee employee = new Employee()
        {
            Id = 1,
            FirstName = "John",
            LastName = "Smith"
        };

        // save it to session
        Session.Add("Employee", employee);
    }

Get it from session. Notice it needs to be cast to an "Employee":

    protected Employee GetEmployee()
    {
        if (Session["Employee"] != null)
        {
            // needs to be cast
            return (Employee)Session["Employee"];
        }
        else
        {
            return null;
        }
    }

I typically wrap this stuff into a property, for ease of use. You usually won't need an object like this in session though... Maybe what you're looking for is: ASP.NET MVC - Set custom IIdentity or IPrincipal

Community
  • 1
  • 1
D-Sect
  • 537
  • 3
  • 10
  • 22