Esp*_*spo 5 asp.net viewstate postback
我按下按钮时尝试设置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;
}
Run Code Online (Sandbox Code Playgroud)
有什么我想念的吗?这是设计文件的表单部分,就像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>
Run Code Online (Sandbox Code Playgroud)
PS:样本非常简单,"使用txtName.Text而不是ViewState"不是正确答案,我需要将信息放在ViewState中.
Kei*_*ith 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());
}
Run Code Online (Sandbox Code Playgroud)
基本顺序是:
| 归档时间: |
|
| 查看次数: |
4180 次 |
| 最近记录: |