-1

I am a new user of ASP.NET and was trying to segregate every page into variables, events and methods. I use a session variable that is used inside almost every method and event. So instead of extracting it from every method and storing it inside a variable, I tried to extract it on a page level. But the keyword 'Session' is not recognised outside a variable. Why is that?

public partial class OnCall_OnCall_History : System.Web.UI.Page
{
#region Variables
string ID = Convert.ToString(Session["ID"]);  //Not allowed 
#endregion

#region PageLoad
protected void Page_Load(object sender, EventArgs e)
{

    if (!IsPostBack)
    {
       string ID  = (string)(Session["ID"]); //Allowed
    }
}
#endregion

}

Bharg
  • 311
  • 1
  • 2
  • 15

3 Answers3

1

That's because you are initialising variables in the declaration, then that assignment will be executed in the constructor. That happens before the properties of the Page object has been set up so that the page is aware that there is a request and a session.

Move those assignments inside an Init event handler. That event happens before the other events, but after the Page object has been set up properly.

That would look like this:

protected string ID;

protected void Page_Init(object sender, EventArgs e) {
  ID = Convert.ToString(Session["ID"]);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

I don't know why but you can use like this

string ID = Convert.ToString(HttpContext.Current.Session["ID"]);

So your code can be

public partial class OnCall_OnCall_History : System.Web.UI.Page
{

    string ID = Convert.ToString(HttpContext.Current.Session["ID"]); 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
              string ID  = (string)(Session["ID"]); //Allowed
         }
    }
}

Here is difference between both
Difference between Session and HttpContext.Current.Session
What is the difference between these two HttpContext.Current.Session and Session - asp.net 4.0

Community
  • 1
  • 1
शेखर
  • 17,412
  • 13
  • 61
  • 117
0

Session object is available inside the context of the ASP.NET page. A request needs to be made for the asp.net page context, and therefore sessions, to be available.

Httpplication -> HttpContext - > HttpSession

I hope this helps.