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;
}

因此,当我第一次单击按钮时,文本框将被更新。但是当我编辑文本并再次单击按钮时,文本框只是恢复到第一次时的状态,即不更新。有人有想法么?

4

6 回答 6

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();
    }
}
于 2013-05-06T05:34:24.383 回答
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;
  }

这是经过测试的代码。

于 2013-05-06T06:41:12.630 回答
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;
}
于 2013-05-06T05:45:19.027 回答
0

您在按钮单击之前获得 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;
  }

话虽如此,如果可以提供帮助,您可能希望完全避免使用 Session。

于 2013-05-06T05:55:34.567 回答
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();
}
于 2013-05-06T05:21:15.913 回答
0

您的页面已回发,这就是为什么它采用您所写的先前值的原因

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)
{
if (Session["Test"] != null) 
        {
            TextBox1.Text = Session["Test"].ToString();
        }
    }
}
于 2013-05-06T05:44:25.243 回答