C# 回发和视图状态

C# 回发和视图状态,c#,viewstate,C#,Viewstate,我见过一些在处理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(Vie

我见过一些在处理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();
        }
    }
有人能指出我们绝对需要检查的情况吗
如果(ViewState[“clicks”]==null)
或程序将不运行?我尝试添加另一个按钮,先单击新按钮,然后单击按钮1,程序仍然运行良好,即使在
按钮2
单击后,它是回发,但在我多次单击按钮1后,程序仍然运行相同的功能。

因为ViewState是字典对象(StateBag)如果试图从不存在的视图状态中获取值,则不会引发异常。为了确保您想要的值处于视图状态,您将执行您所要求的操作

此外,如果您正在开发一个控件或共享组件,该控件或组件将在禁用ViewState的页面上使用,则ViewState值的ViewState将为null

这部分内容摘自:

有人能指出我们绝对需要检查的情况吗 如果(ViewState[“clicks”]==null)或程序将不运行

当然可以:

这将中断,因为您试图调用某个方法,但在第一个页面加载时,它将为null。如果您问为什么我们在分配它之前先测试它是否为null,那么您应该知道If null测试不是为了分配,而是为了设置文本框文本的行。有了代码中的IF块,我们可以保证在使用ViewState[“clicks”]时,ToString()不会尝试对null调用ToString()(因为ViewState[“clicks”]已经在别处设置,或者它已经被这个IF块默认)

点击按钮2后,该程序仍然是回发的 在我多次单击按钮1后,功能相同


但是。。当它是回发时,整个代码块根本不会运行。。如果在您不完全需要的情况下,它是回发的,那么ViewState将永远不会在页面加载中使用;但是,如何处理ViewState的本机类型?如果没有值,则需要某种类型的特殊处理。对于原生类型,我指的是整数、日期时间和Guid值……我最好奇的是如何在表单中添加另一个按钮,首先单击它,这样我就知道页面是回发的,但代码仍然运行良好。很高兴知道为什么我可以访问一个从未显式声明过的变量!:)我的评论是,该程序仍然可以正常运行。原因已在上面的答复中解释。
    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();
        }
    }