PostBack and ViewState

本文关键字:ViewState and PostBack | 更新日期: 2023-09-27 18:16:40

我看到一些代码在处理ViewState变量时看起来很习惯,比如

protected void Page_Load(object sender, EventArgs e)
    {
        //find if this is the initial get request
        //after you click a button, this code will not run again
        if (!IsPostBack)
        { 
            if(ViewState["clicks"] ==null)
            {
                ViewState["clicks"] = 0;
            }
            //we're using the ViewState[clicks] to initialize the text in the text box
            TextBox1.Text = ViewState["clicks"].ToString();
        }
    }

谁能指出一个我们绝对需要检查的情况是if(ViewState["clicks"] == null)还是程序无法运行?我尝试添加另一个按钮,首先单击新按钮,然后单击Button1,程序仍然运行良好,即使在Button 2单击后它是回发,程序仍然在我多次单击按钮1后运行相同。

PostBack and ViewState

因为ViewState是一个字典对象(StateBag),如果你试图从ViewState中获取一个不存在的值,不会抛出异常。要确保你想要的值在viewstate中,你需要做你所要求的。

同样,如果你正在开发一个控件或共享组件,它将在ViewState禁用的页面上使用,那么ViewState的值将为null。

部分摘自:http://msdn.microsoft.com/en-us/library/ms228048%28v=vs.85%29.aspx

谁能指出一个我们绝对需要检查的情况如果(ViewState["clicks"] == null)或程序将不运行?

确定:

    protected void Page_Load(object sender, EventArgs e)
    {
        //find if this is the initial get request
        //after you click a button, this code will not run again
        if (!IsPostBack)
        {
            //if (ViewState["clicks"] == null)
            //{
            //    ViewState["clicks"] = 0;
            //}
            //we're using the ViewState[clicks] to initialize the text in the text box
            TextBox1.Text = ViewState["clicks"].ToString();
        }
    }

这将打破,因为你试图调用一个方法上的东西,你需要非空,但在第一个页面加载,它将为空。如果你问为什么我们在赋值之前先测试它是否为空,那么你应该知道If -null测试不是为了赋值,而是为了设置文本框文本的行。有了这个IF块,我们就可以保证,当我们使用ViewState["clicks"].ToString()时,我们不会尝试在null上调用ToString()(因为ViewState["clicks"]要么已经在别处设置,要么已经被这个IF块默认)

按钮2点击后被回发,程序仍然点击按钮1多次后效果还是一样的

但. .当它是回发时,整个代码块根本不会运行。如果它是回发

,则ViewState永远不会在PageLoad中使用。