繁体   English   中英

ASP.NET回发问题

[英]ASP.NET Postback Issues

我正在学习ASP.NET,但我不明白这里发生了什么。

文件后面的代码:

protected void Page_Load(object sender, EventArgs e)
{
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForColor = System.Drawing.Color.Blue;
}

基本上所有的标签都告诉您文本框的颜色和文本是什么。 当您按下按钮时,它将颜色更改为蓝色,并且页面将重新加载。

为什么在第一次按下按钮并重新加载页面时,标签没有更新为正确的信息? 您必须再次按下该按钮才能读取该文本框为红色。

谁能提供这种行为的解释? 以及如何更改Page_Load方法来解决此问题?

在控制事件之前正在处理Page_Load事件。 请参阅http://msdn.microsoft.com/zh-cn/library/ms178472.aspx上的页面生命周期说明。 要解决此问题,请修改代码,以使Page_Load和Button_Click处理程序调用相同的方法来设置标签值。 如果该方法不是POSTBACK,则仅执行Page_Load。

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       SetUpLabel();
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForeColor = System.Drawing.Color.Blue;

    SetUpLabel();
}

private void SetUpLabel()
{
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
}

您需要在Page_Load中编写代码,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
  if(!IsPostBack) //This condition allows a code to execute once when your page is load first time.
   {
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
   }
}

protected void Button1_Click(object sender, EventArgs e)
{
    TextBox1.Text = "Some more text";
    TextBox1.ForColor = System.Drawing.Color.Blue;

    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();

}

试试看,只需尝试此代码,此代码始终有效,不需要额外的代码

bool IsClick=false;
protected void Page_Load(object sender, EventArgs e)
{    
    Label1.Text = "TextBox1.Text = " + TextBox1.Text + "<br />";
    Label1.Text += "TextBox1.Forecolor = " TextBox1.ForeColor.ToString();
    if(IsClick)
    {
    TextBox1.Text = "Some more text";
    TextBox1.ForeColor = System.Drawing.Color.Blue;
    }
}


protected void Button1_Click(object sender, EventArgs e)
{
  IsClick=true;
}

这是我的主意

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM