2010-02-26 29 views
6

我正在構建一個Asp.net應用程序。我需要在會話中保存一個HashTable。我應該在asp.net中聲明會話變量

在頁面加載我寫

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

這裏的問題是,當用戶刷新頁面,會話[「AttemptCount」]也得到刷新。 我想知道我應該在哪裏申報

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

所以我SEESION沒有得到refeshed。

編輯在Global.asax中,只要用戶打開網站,此會話就會開始。我只想在用戶轉到特定頁面時創建此會話。即Login.aspx

回答

14

做它在Session_Start方法在你Global.asax是這樣的...

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

更新:

然後簡單地只是做一個檢查,看看是否會話變量存在,如果它不只有然後創建變量。你可以把它貼在屬性使事情更清潔,像這樣......

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

然後你可以只對房地產AttemptCount打電話,無論你需要的是這樣的...

public void doEvent(object sender, EventArgs e) 
{ 
    AttemptCount.Add("Key1", "Value1"); 
} 
+0

在Global.asax中,本屆會議將得到一旦用戶打開網站就開始了。我只想在用戶轉到特定頁面時創建此會話。即Login.aspx – 2010-02-26 20:42:52

+0

我已經更新了我的答案,您只需通過檢查null來檢查它是否存在 – 2010-02-26 20:53:21

+0

你在散列表中存儲什麼?這是用戶嘗試登錄的次數嗎? – 2010-02-26 20:57:23

0

看看Global.asax和Application_Started(我認爲),並且還有一個用於啓動會話。

2

測試,如果它存在的第一

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

雖然在session_start是更好的,你只需要使用它在一個頁面上,但你可以爲每個會話創建它。

3

你可以做這樣的屬性在你的頁面:

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

那麼你可以使用它,而無需擔心:

protected void Page_Load(object sender, EventArgs e) 
{ 
    this.AttemptCount.Add("key", "value"); 
} 
1
Hashtable hastable_name=new Hashtable() 
Session["AttemptCount"]=hastable_name