Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET; Several session variables or a "container object"?

I have several variables that I need to send from page to page... What is the best way to do this?

Just send them one by one:

string var1 = Session["var1"] == null ? "" : Session["var1"].ToString();
int var2 = Session["var2"] == null ? 0 : int.Parse(Session["var2"].ToString());

and so on...

Or put them all in some kind of container-object?

struct SessionData
{
    public int Var1 { get; set; }
    public string Var2 { get; set; }
    public int Var3 { get; set; }
}

--

SessionData data = Session["data"] as SessionData;

What is the best solution? What do you use?

like image 868
Christian Wattengård Avatar asked Jun 21 '10 13:06

Christian Wattengård


2 Answers

A hybrid of the two is the most maintainable approach. The Session offers a low-impedance, flexible key-value pair store so it would be wasteful not to take advantage of that. However, for complex pieces of data that are always related to each other - for example, a UserProfile - it makes sense to have a deeply nested object.

like image 66
Rex M Avatar answered Oct 24 '22 19:10

Rex M


If all the data that you're storing in the Session is related, then I would suggest consolodating it into a single object like your second example:

public class UserData
{
    public string UserName { get; set; }
    public string LastPageViewed { get; set; }
    public int ParentGroupId { get; set; }
}

And then load everything once and store it for the Session.

However, I would not suggest bundling unrelated Session data into a single object. I would break each seperate group of related items into their own. The result would be something of a middleground between the two hardline approaches you provided.

like image 29
Justin Niessner Avatar answered Oct 24 '22 20:10

Justin Niessner