Where I should declare a session variable in asp.net

后端 未结 5 616
醉话见心
醉话见心 2021-01-02 14:33

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, Even         


        
相关标签:
5条回答
  • 2021-01-02 15:08

    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");
    }
    
    0 讨论(0)
  • 2021-01-02 15:09

    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.

    0 讨论(0)
  • 2021-01-02 15:11
    Hashtable hastable_name=new Hashtable()
    Session["AttemptCount"]=hastable_name
    
    0 讨论(0)
  • 2021-01-02 15:13

    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");
    }
    
    0 讨论(0)
  • 2021-01-02 15:23

    Look at Global.asax and the Application_Started (I think) and there is one for session started too.

    0 讨论(0)
提交回复
热议问题