5

我试图在按下按钮时设置 ViewState 变量,但它仅在我第二次单击按钮时才起作用。下面是代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
    }
}

private string YourName
{
    get { return (string)ViewState["YourName"]; }
    set { ViewState["YourName"] = value; }
}


protected void btnSubmit_Click(object sender, EventArgs e)
{
    YourName = txtName.Text;

}

有什么我想念的吗?这是设计文件的表单部分,非常基本,就像POC一样:

<form id="form1" runat="server">
<div>
Enter your name: <asp:TextBox runat="server" ID="txtName"></asp:TextBox>
<asp:Button runat="server" ID="btnSubmit" Text="OK" onclick="btnSubmit_Click" />
<hr />
<label id="lblInfo" runat="server"></label>
</div>
</form>

PS:示例非常简化,“使用txtName.Text代替 ViewState”不是正确答案,我需要将信息放在 ViewState 中。

4

1 回答 1

12

Page_Load之前发生火灾btnSubmit_Click

如果您想在回发事件触发后做某事,请使用Page_PreRender.

//this will work because YourName has now been set by the click event
protected void Page_PreRender(object sender, EventArgs e)
{
    if (Page.IsPostBack)
        lblInfo.InnerText = String.Format("Hello {0} at {1}!", YourName, DateTime.Now.ToLongTimeString());
}

基本顺序如下:

  • 页面初始化触发(初始化无法访问 ViewState)
  • 读取 ViewState
  • 页面加载触发
  • 任何事件触发
  • PreRender 触发
  • 页面呈现
于 2008-09-03T10:48:15.817 回答