从服务器端获取TextBox控件的Set值

本文关键字:Set 控件 TextBox 服务器端 获取 | 更新日期: 2023-09-27 17:59:52

假设我在ASP的页面加载上有这段代码。NET Webform

protected void Page_Load(object sender, EventArgs e)
{
    TextBox1.Text = "123";
}

这是我在aspx文件中的控件

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

如果我将文本框数据从123更改为12548或前端的任何内容,然后单击按钮现在这是我的代码背后的按钮点击事件

protected void Button1_Click(object sender, EventArgs e)
{
    string s = TextBox1.Text;
}

现在在TextBox1.Text中,我应该得到12548或更新的值,而不是我已经在页面加载中设置的123。

现在我想获得更新后的值,我该如何以正确的方式进行操作。

从服务器端获取TextBox控件的Set值

将其包装在NOT is Postback 中

  protected void Page_Load(object sender, EventArgs e)
{ 
 if(!IsPostBack)
    {
      TextBox1.Text = "123";
    }
}

或者完全移除:

protected void Page_Load(object sender, EventArgs e)
{
  //not here
}
<asp:TextBox ID="TextBox1" Text="123" runat="server"></asp:TextBox>

修改Page_Load如下:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostback)
    {
        TextBox1.Text = "123";
    }
}

问题是"在ASP.Net中,每次您导致任何类型的回发,包括处理按钮单击等事件时,您都在使用页面类的全新实例,该实例必须从头开始重建。您以前在服务器上构建页面所做的任何工作都将消失。这意味着运行整个页面生命周期,包括页面加载代码,而不仅仅是单击代码。

每次在前端执行任何事件时,它都会重新创建页面并再次调用pageload方法,页面实际上会重置。为了避免这种情况,应该使用以下代码

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostback)
        {
             //default code
        }
    }