Web窗体是无状态的。
要保留某些状态必须用到ASP.NET的内置对象。
在ASP.NET页面间传递数据的方式有几种:
1.传递数据给页面本身
使用ViewState对象。
2.传递给当前页面链接到的另一页面
使用Request.QueryString
3.传递给没有直接关联的页面
使用Session、Cookie或全局变量。
如上,ViewState用来给页面本身传递数据用。比如我们有一个变量,值为:100,然后页面放一个按钮,每点一次给这个变量加1,然后显示到一个TextBox中,通常应该是这样的代码:
private int id;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
id = 100;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
id++;
TextBox1.Text = id.ToString();
}
但是,实际运行一下会发现结果不是我们预想的。这是因为:当页面提交或刷新后,由于Web页面的无状态性,这个变量的值会消失,因此通常把它保存到ViewState中,在刷新后从ViewState中取回该值。改用下面的代码:
private int id;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["id"]==null)
{
id = 100;
ViewState["id"] = id;
}
else
{
id =(int) ViewState["id"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
id++;
TextBox1.Text = id.ToString();
ViewState["id"] = id;
}
就可以得到我们想要的结果。
要保留某些状态必须用到ASP.NET的内置对象。
在ASP.NET页面间传递数据的方式有几种:
1.传递数据给页面本身
使用ViewState对象。
2.传递给当前页面链接到的另一页面
使用Request.QueryString
3.传递给没有直接关联的页面
使用Session、Cookie或全局变量。
如上,ViewState用来给页面本身传递数据用。比如我们有一个变量,值为:100,然后页面放一个按钮,每点一次给这个变量加1,然后显示到一个TextBox中,通常应该是这样的代码:
private int id;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
id = 100;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
id++;
TextBox1.Text = id.ToString();
}
但是,实际运行一下会发现结果不是我们预想的。这是因为:当页面提交或刷新后,由于Web页面的无状态性,这个变量的值会消失,因此通常把它保存到ViewState中,在刷新后从ViewState中取回该值。改用下面的代码:
private int id;
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["id"]==null)
{
id = 100;
ViewState["id"] = id;
}
else
{
id =(int) ViewState["id"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
id++;
TextBox1.Text = id.ToString();
ViewState["id"] = id;
}
就可以得到我们想要的结果。