在使用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之后仍然运行相同。
发布于 2013-06-03 23:48:31
因为ViewState是一个字典对象(StateBag),所以如果您试图从视图状态获取一个不存在的值,则不会引发任何异常。为了确保你想要的值在视图状态中,你可以按照你所要求的去做。
此外,如果您正在开发的控件或共享组件将在禁用了ViewState的页面上使用,则对于ViewState值,ViewState将为null。
本文的一小部分摘自:http://msdn.microsoft.com/en-us/library/ms228048%28v=vs.85%29.aspx
发布于 2013-06-04 00:00:35
有人能指出一种情况,我们绝对需要检查(ViewState“点击”== 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();
}
}这将会中断,因为您正在尝试调用某个方法,但在第一个页面加载时,它将是空的。如果你问为什么我们在赋值之前先测试它是否为null,那么你应该知道if-null测试并不是为了赋值的好处,而是为了设置文本框文本的行的好处。有了代码中的IF块,我们可以保证当我们开始使用ViewState"clicks".ToString()时,我们不会试图在null上调用ToString() (因为ViewState"clicks“已经在别处设置了,或者它已经被IF设置为默认值)
在Button 2点击后它是一个回发,程序在我多次点击button 1之后仍然运行相同
但是..。当它是回发时,整个代码块根本不会运行。如果是回发,则永远不会在PageLoad中使用ViewState
https://stackoverflow.com/questions/16900576
复制相似问题