如何在 C# 中声明会话变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16407502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to declare session variable in C#?
提问by Carrie
I want to make a new session, where whatever is typed in a textbox is saved in that session. Then on another aspx page, I would like to display that session in a label.
我想创建一个新会话,在该会话中保存在文本框中键入的任何内容。然后在另一个 aspx 页面上,我想在标签中显示该会话。
I'm just unsure on how to start this, and where to put everything.
我只是不确定如何开始这个,以及把所有东西放在哪里。
I know that I'm going to need:
我知道我需要:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["newSession"] != null)
{
//Something here
}
}
But I'm still unsure where to put everything.
但我仍然不确定把所有东西放在哪里。
采纳答案by Tim Schmelter
newSessionis a poor name for a Sessionvariable. However, you just have to use the indexer as you've already done. If you want to improve readability you could use a property instead which can even be static. Then you can access it on the first page from the second page without an instance of it.
newSession是一个糟糕的Session变量名称。但是,您只需要像之前一样使用索引器即可。如果你想提高可读性,你可以使用一个甚至可以是静态的属性。然后,您可以在没有实例的情况下从第二页访问第一页。
page 1 (or wherever you like):
第 1 页(或任何您喜欢的地方):
public static string TestSessionValue
{
get
{
object value = HttpContext.Current.Session["TestSessionValue"];
return value == null ? "" : (string)value;
}
set
{
HttpContext.Current.Session["TestSessionValue"] = value;
}
}
Now you can get/set it from everywhere, for example on the first page in the TextChanged-handler:
现在你可以从任何地方获取/设置它,例如在TextChanged-handler的第一页上:
protected void TextBox1_TextChanged(Object sender, EventArgs e)
{
TestSessionValue = ((TextBox)sender).Text;
}
and read it on the second page:
并在第二页阅读:
protected void Page_Load(Object sender, EventArgs e)
{
this.Label1.Text = Page1.TestSessionValue; // assuming first page is Page1
}

