题
我试图在按下按钮时设置 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>
附: 该示例非常简化,“使用 txtName.Text
而不是 ViewState”不是正确的答案,我需要信息位于 ViewState 中。
解决方案
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());
}
基本顺序是:
- 页面 init 触发(init 无法访问 ViewState)
- ViewState 已读取
- 页面加载引发火灾
- 任何事件都会发生
- 预渲染火灾
- 页面渲染
不隶属于 StackOverflow