Introduction
Coming from an app development background, something I would do is create a class, say CurrentUser,
and give a bunch of static variables that I need to access throughout the program. This then allows me to only fetch
the data once, taking a tiny bit of pressure off of the server.
The problem with doing this in ASP is that the static variables will stored on the server, and anyone who logs in after
the first person will just get their values instead of their own. Using Session there is a very easy, elegant work around.
Using the code
Start of lets create a CurrentUser class. Lets assume that throughout our application it is important to know their age,
surname, and current city. We create these three variables as properties. Since we only need to retrieve the information, we only set a getter.
The first thing we do is check whether our value exists in the session. If it is null, we call Initialize
.
public class CurrentUser
{
public static string Surname
{
get
{
if (String.IsNullOrEmpty(Session["surname"]))
Initialize();
return (string)Session["surname"];
}
}
public static string City
{
...
}
public static string City
{
...
}
private void Initialize()
{
MyDataObject obj = FetchMyData();
Session.Add("surname", obj.Surname);
....
}
}
That is pretty much it. It's not meant to be a super in depth article, just a little tip for you guys just starting on ASP. Hope you find it useful.
History
Version 1: Published.
I've been passionate about coding since I can remember. My early years of coding involved QBasic and VB. My love for video games lured me into learning Game Maker and spent 2 years playing around with that. I have been programming in C# for a year now, and love learning new things.