2013-05-06 77 views
-1

例如,我有如何在C#中保存會話?

Session["PatientName"] = patientNameTextBox.Text; 

信息輸入到textbox後,按鈕被點擊保存會話,但我不太清楚該怎麼做。

任何幫助表示讚賞。謝謝 :)。

+0

你上面的代碼會保存會話中的文本,你的意思是保存嗎?你是否在檢索價值時遇到問題,或者你是否想將其保存在永久存儲器中 – Habib 2013-05-06 05:39:59

+0

你的會話很好走 – 2013-05-06 06:19:16

+0

@Habib:你目前的狀況如何? – 2013-05-06 07:46:48

回答

3

如果您針對Button_Click事件放置代碼,則上面的行Session["PatientName"] = patientNameTextBox.Text;會將Text值保存在會話中。爲了找回它回來,你可以這樣做:

string patientName = Session["PatientName"] != null ? Session["PatientName"].ToString() 
                : ""; //or null 

切記不要過多信息存儲在會話,因爲它們是維持服務器爲每個用戶。

+0

可以簡化爲'string parientName = Session [「PatientName」] ?? 「」;'。那就是如果你想首先避免null。 – SimpleVar 2013-05-06 05:29:54

+0

@YoryeNathan,是的,也可以使用null合併運算符。謝謝 – Habib 2013-05-06 05:30:49

+0

順便說一句,我不確定這是回答他的問題。現在,他有一個變量的數據,但我感覺他已經知道如何做到這一點(所有的複雜性......) - 他想以某種方式保存它。但是,想要的節約時尚卻很模糊。 – SimpleVar 2013-05-06 05:36:18

1

您可以檢查是否值是會話裏面做這個:

if (Session["PatientName"] != null) 
    ... 

您可以通過執行此檢索值:

// Remember to cast it to the correct type, because Session only returns objects. 
string patientName = (string)Session["PatientName"]; 

如果您不能確定是否有內部值,你想要一個默認值,試試這個:

// Once again you have to cast. Use operator ?? to optionally use the default value. 
string patientName = (string)Session["PatientName"] ?? "MyDefaultPatientName"; 

把你的答案放回到一個文本框或標籤:

patientLabel.Text = patientName; 
0

這怎麼可以節省單擊按鈕時會話:

protected void buttonSaveSession_Click(object sender, EventArgs e) 
{ 
    string patientName = textBoxPatientName.Text; 
    Session["PatientName"] = patientName; 
} 

這是你可以檢查或某人有一個會話:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["PatientName"] != null) 
    { 
     //Your Method() 
    } 
}