View state
我们需要知道的是:ViewState在ASP.net 2.0的存在形式是集合(Dictionary collection),如下面的代码:
ViewState["Counter"] = 1;
如果集合中不存在Counter那么就自动创建一个,如果有将其覆盖,还有一点需要注意的是当你接受数据时,由于你将会使用KEYname,同时你需要将数据类型转化你需要的类型,因为ASP.net将所有的数据类型设置为Geneic Object,如下面的代码:
--------------------------------------------------------------------------------
int Counter;
if(ViewState["Counter"] != null)
{
Counter = (int)ViewState["Counter"];
}
--------------------------------------------------------------------------------
然后我们需要学会如何将自己的数据保存在ViewState中,首先需要注意的是将你的数据Serialzation掉,在这之前我们需要知道条件:
你的类必须支持Serialzation
所有的类的Private成员变量必须转化为Serialzation.
下面我们来看个简单的Example:
[Serialation]
Public Class Name
{
string Firstname;
string Secondname;
public Name(String F,String S)
{
Firstname = F;
Secondname = S;
}
}
-----------------------------------
Name n = new Name("stone","li");
ViewState["Name"] = n;
//
Name k;
k = (Name)ViewState["Name"];
-----------------------------------
下面我们来作一个复杂的Example
我们建立一个表单然后将多有的数据存放到hashtable中,Hashtabke支持Serialation,然后放在ViewState中,然后在取出
-----------------------------------
// This will be created at the beginning of each request.
Hashtable textToSave = new Hashtable();
用来存储control类型为TextBox的ID和TEXT
private void SaveAllText(ControlCollection controls, bool saveNested)
{
foreach (Control control in controls)
{
if (control is TextBox)
{
// Add the text to a collection.
textToSave.Add(control.ID, ((TextBox)control).Text);
}
if ((control.Controls != null) && saveNested)
{
SaveAllText(control.Controls, true);
}
}
}
-------------------------------------
if (ViewState["ControlText"] != null)
{
SaveAll(form1.Controls,true);
ViewState["ALL"] = texttosave;
// Retrieve the hashtable.
Hashtable savedText = (Hashtable)ViewState["ControlText"];
// Display all the text by looping through the hashtable.
lblResults.Text = "";
foreach (DictionaryEntry item in savedText)
{
lblResults.Text += (string)item.Key + " = " +
(string)item.Value + "<br />";
}
}