Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where I should declare a session variable in asp.net

I am building a Asp.net Application. I need to save a HashTable in a session.

At page load i am writing

 protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       Session["AttemptCount"]=new Hashtable(); //Because of this line.
    }   
}

Here problem is, when a user refresh the page, session["AttemptCount"] also get refreshed. I want to know where should I declare

Session["AttemptCount"]=new Hashtable();

So that my seesion do not get refeshed.

EDIT In Global.asax, this session will get started, as soon as user opens the website. I want to creat this session only if user go to a particular page. i.e Login.aspx

like image 995
Vaibhav Jain Avatar asked Feb 26 '10 20:02

Vaibhav Jain


3 Answers

Do it in the Session_Start method in your Global.asax like so...

protected void Session_Start(object sender, EventArgs e)
{
    Session["AttemptCount"]=new Hashtable();
}

Update:

Then simply just do a check to see if the session variable exists, if it doesn't only then create the variable. You could stick it in a property to make things cleaner like so...

public Hashtable AttemptCount
{
    get 
    {
        if (Session["AttemptCount"] == null)
            Session["AttemptCount"]=new Hashtable();
        return Session["AttemptCount"];
    }
}

And then you could just call on the property AttemptCount wherever you need like so...

public void doEvent(object sender, EventArgs e)
{
    AttemptCount.Add("Key1", "Value1");
}
like image 62
Naeem Sarfraz Avatar answered Nov 12 '22 18:11

Naeem Sarfraz


You could make a property like this in your page:

protected Hashtable AttemptCount
{
  get
  {
    if (Session["AttemptCount"] == null)
      Session["AttemptCount"] = new Hashtable();
    return Session["AttemptCount"] as Hashtable; 
  }
}

then you can use it without having to worry:

protected void Page_Load(object sender, EventArgs e)
{
  this.AttemptCount.Add("key", "value");
}
like image 21
M4N Avatar answered Nov 12 '22 17:11

M4N


test if it exists first

 protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
       if(Session["AttemptCount"] == null)
       {
          Session["AttemptCount"]=new Hashtable(); //Because of this line.
       }
    }   
}

though the session_start is better, you only need to uses it on one page but you can create it for each session.

like image 2
Pharabus Avatar answered Nov 12 '22 18:11

Pharabus