我正在尝试在按下按钮时设置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中。
答案 0 :(得分: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());
}
基本顺序是: