2013-05-06 73 views
2

每当我尝试更新之前输入的会话变量时,它都不会更新。会话变量无法更新

继承人什么我谈论的例子:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["Test"] != null) 
    { 
     TextBox1.Text = Session["Test"].ToString(); 
    } 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
    Session["Test"] = TextBox1.Text; 
} 

所以,当我点击按钮,在第一时间,文本框将被更新。但是,当我编辑文本并再次单击按钮时,文本框只是恢复到它第一次即不更新。有人有主意吗?

+0

哪个会话变量,你正在尝试上调 – 2013-05-06 05:17:48

+0

TextBox1将始终有会话[“盒”]价值,你没有更新代码中的任何地方,所以它不会更新 – 2013-05-06 05:19:49

+0

为什么不只是删除会话。 – StackOverflowUser 2013-05-07 08:28:19

回答

2

所以,当我点击按钮,在第一时间,文本框将会 更新。但是,当我编辑的文本,然后再次单击该按钮, 文本框只是恢复到什么是第一次

我相信那是因为你正在这样做完全一样的是:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["Test"] != null) 
    { 
     TextBox1.Text = Session["Test"].ToString(); 
    } 
} 

在您拥有的代码应该检查页面加载是否由回发(单击按钮)引起。所以,你应该这样做:

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack && Session["Test"] != null) 
    { 
     TextBox1.Text = Session["Test"].ToString(); 
    } 
} 
+0

谢谢!每个人的回答都非常有帮助。干杯 – 2013-05-06 10:15:25

0

做这样的

protected void Page_Load(object sender, EventArgs e) 
{ 
if (!Page.IsPostBack) 
    {    
     Session["Test"] = "";   
    } 
    if (Session["Test"] != null) 
    {  
     Session["Test"] = ASPxTextBox1.Text;    
    } 
} 


protected void ASPxButton1_Click(object sender, EventArgs e) 
{ 
    ASPxTextBox1.Text = Session["Test"].ToString(); 
} 
0

您页回这就是为什么它走以前的值,你已经写

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (Session["Test"] != null) 
    { 
     TextBox1.Text = Session["Test"].ToString(); 
    } 
} 

INT这段代码的文本框中的文本将与前恢复你之前输入的值,所以 你的代码应该是

protected void Page_Load(object sender, EventArgs e) 
    { 

if(!IsPostBack) 
{ 
if (Session["Test"] != null) 
     { 
      TextBox1.Text = Session["Test"].ToString(); 
     } 
    } 
} 
0

这应该工作

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!Page.IsPostBack) 
    { 
     if (Session["Test"] != null) 
     { 
      TextBox1.Text = Session["Test"].ToString(); 
     } 
    } 
} 
protected void Button1_Click(object sender, EventArgs e) 
{ 
    Session["Test"] = TextBox1.Text; 
} 
0

在Button Click之前,您正在获取Page_Load事件,因此您的Page_Load正在使用Session中的先前值覆盖TextBox1.Text的值。这就是为什么它在第一次设置后永远不会改变的原因。

检查是否不响应上的Page_Load后是这样的:

protected void Page_Load(object sender, EventArgs e) 
    { 
    if (!IsPostBack) 
    { 
     TextBox1.Text = (Session["Test"] ?? "").ToString(); 
    } 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
    Session["Test"] = TextBox1.Text; 
    } 

虽这么说,你可能要避免使用完全如果可以帮助会话。

1
protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     if (Session["Test"] != null && Session["Test"].ToString().Length > 0) 
     { 
      TextBox1.Text = Session["Test"].ToString(); 
     } 
    } 
    Session["Test"] = string.Empty; 
} 

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Session["Test"] = TextBox1.Text; 
    } 

这是测试代码。