在页面的Load事件之前更新ViewState

时间:2014-01-21 06:19:22

标签: c# asp.net viewstate

是否有任何方法可以在页面的Load事件之前从页面事件(例如按钮单击)更新ViewState?

据我所知,事件处理程序只会在加载事件后调用,但有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

由于ASP .net页面的生命周期。将状态传递给可以访问OnPageLoad的服务器的唯一方法是在页面上使用HiddenField,在客户端使用Javascript更新。

答案 1 :(得分:0)

 protected void Page_Load(object sender, EventArgs e)
    {
        if (ViewState["val"] != null)
        {
            int s = Convert.ToInt32(ViewState["val"]);
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (ViewState["val"] != null)
        {
            int s = Convert.ToInt32(ViewState["val"]);
            s = s + 5;
            ViewState["val"] = s;
        }
        else
        {
            ViewState["val"] = 6;
        }
    }

这是我在我的机器上测试的代码 并且在页面加载时我每次都获得updaetd值,