In my ASP.Net application, Iam using 1 Master Page and 2 Content Page. I need to access a session variable across the application for individual user like "UserID".
Iam setting this Variable only in content page, so based upon the variable when another content page is opened, it should prompt a message.
Ex :
In Content Page1.aspx.cs
Session["UserId"] = "USR15289";
In Master Page.aspx
Trying to access that session variable in JS
var UserId= '<%=Session["UserId"] %>';
When I click the Content Page 1, the session variable is set correctly. Now Iam clicking Content Page 2, but the session variable in Master Page is showing as "". Then If I click the Content Page 1 again, now the session variable is showing as "USR15289".
Problem is Session variable is not displaying on the first click, but showing only in second click.
What may be the problem ? am I missing some thing ?
As my Experienced:
Much Better to use Cookies than Session.
Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);
HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Reading back:
if(Request.Cookies["userName"] != null)
Label1.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);
if(Request.Cookies["userName"] != null)
{
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);
}
See this link.