SessionState
Passing variables between pages is quite simple. The server keeps track of each user's session and the variables associated with that session. To add my own variables, I simply use this single line of code:
Session["member"] = txtMember.Text;
That line of code reads the text entered in the txtMember box and stores it in the Session variable with a key of "member". I can access the variable as easily as I created it. To set a text box to the current member, use this line of code:
txtMember.Text = Session["member"];
That's all there is to it. Simple, right? ASP.NET automatically differentiates between different concurrent users so you don't have to worry about it.
Cookies
Now let's say I want to store the member's name so that they are automatically logged on when they visit the site. This requires a cookie. It's a few more lines of code than the Session variable but not much more difficult.
To create the cookie:
HttpCookie cookie = new HttpCookie("MySite"); cookie.Values.Add("member",txtMember.Text); cookie.Expires = DateTime.MaxValue; // Never Expires Response.AppendCookie(cookie); |
...
DateTime dt = DateTime.Now;
TimeSpan span = new TimeSpan(7,0,0,0);
cookie.Expires = dt.Add(span);
...
|
HttpCookie cookie = Request.Cookies["MySite"];
if (cookie != null)
result = cookie.Values["member"];
|
This code was accepted as a tutorial on Devhood!
Disclaimer:
By installing this software, you assume complete responsibility for any
damage that may occur to your system or your oldest child. I assume no
liability. Besides, if you tried to sue me you wouldn't get much.
May cause cancer in pregnant
lab rats on rainy days in Arkansas. Violators will be persecuted. Do not
pass Go, do not collect $200, go directly to jail. An apple a day keeps the
doctor away. Caffeine-free (although I am probably not). Look both ways
before crossing the road. Don't put that quarter in your mouth, you don't
know where it's been. Do not use in areas of high radiation. Do not use
while being chased by a rabid African tiger (a healthy one maybe, but not a
rabid one). I am not responsible for any lost or stolen brain cells. And
last, but not least, have fun!