加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 在回发上设置viewstate

发布时间:2020-12-16 03:30:10 所属栏目:asp.Net 来源:网络整理
导读:我按下按钮时尝试设置ViewState变量,但它只在我第二次单击按钮时才有效.这是代码隐藏: protected void Page_Load(object sender,EventArgs e){ if (Page.IsPostBack) { lblInfo.InnerText = String.Format("Hello {0} at {1}!",YourName,DateTime.Now.ToLon
我按下按钮时尝试设置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中.

解决方法

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}!",DateTime.Now.ToLongTimeString());
}

基本顺序是:

>页面init触发(init无法访问ViewState)>读取ViewState>页面加载火灾>任何事件都会发生> PreRender开火>页面渲染

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读