Car*_*rie 3 c# session declare
我想创建一个新会话,在该会话中保存文本框中键入的任何内容.然后在另一个aspx页面上,我想在标签中显示该会话.
我只是不确定如何开始这个,以及放置一切的地方.
我知道我需要:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["newSession"] != null)
{
//Something here
}
}
Run Code Online (Sandbox Code Playgroud)
但我仍然不确定在哪里放一切.
Tim*_*ter 11
newSessionSession变量的名称很差.但是,您只需使用索引器,就像您已经完成的那样.如果您想提高可读性,可以使用属性,甚至可以是静态属性.然后,您可以在第二页的第一页上访问它而不使用它的实例.
第1页(或任何你喜欢的地方):
public static string TestSessionValue
{
get
{
object value = HttpContext.Current.Session["TestSessionValue"];
return value == null ? "" : (string)value;
}
set
{
HttpContext.Current.Session["TestSessionValue"] = value;
}
}
Run Code Online (Sandbox Code Playgroud)
现在您可以从任何地方获取/设置它,例如在TextChanged-handler 的第一页上:
protected void TextBox1_TextChanged(Object sender, EventArgs e)
{
TestSessionValue = ((TextBox)sender).Text;
}
Run Code Online (Sandbox Code Playgroud)
并在第二页上阅读:
protected void Page_Load(Object sender, EventArgs e)
{
this.Label1.Text = Page1.TestSessionValue; // assuming first page is Page1
}
Run Code Online (Sandbox Code Playgroud)