我按下按钮时尝试设置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一样非常基本:
PS:样本非常简单,"使用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
页面加载火灾
任何事件都会发生
PreRender开火
页面渲染