在回发上设置viewstate

时间:2008-09-03 10:37:43

标签: asp.net postback viewstate

我正在尝试在按下按钮时设置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中。

1 个答案:

答案 0 :(得分:12)

Page_LoadbtnSubmit_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());
}

基本顺序是:

  • Page init触发(init无法访问ViewState)
  • 阅读ViewState
  • Page load fires
  • 任何事件开火
  • PreRender开火
  • 页面渲染