我们在用.net开发web应用程序的时候经常会用到ViewState,真是个很有用的东东,那么ViewState到底是何方人氏那?
其实ViewState只是StateBag类的一个实例,所以我们平时看到的只是冰山的一角,现在我们就来探究一下下面的更大的冰山.
NET Framework类库 StateBag 类
1. 概述
管理 ASP.NET 服务器控件(包括页)的视图状态。无法继承此类。
Control.ViewState 属性是 StateBag 类的实例。
有关此类型所有成员的列表,请参阅 StateBag 成员。
System.Object
System.Web.UI.StateBag
[定义][C#]
public sealed class StateBag : IStateManager, IDictionary,ICollection, IEnumerable
[线程安全]
此类型的所有公共静态(Visual Basic 中为 Shared)成员对多线程操作而言都是安全的。但不保证任何实例成员是线程安全的。
[备注]
页或控件的视图状态是该页或控件的累计属性值或视图。可以通过 Control.ViewState 属性访问此类。
此类是所有 HTML 和 Web 服务器控件的主存储机制。它将属性/值对存储为与控件关联的字符串。仅在为页请求执行 OnInit 方法后,它才跟踪这些属性的更改,并将更改保存到页或控件的视图状态。
在控件处理生存期的任何阶段可以从此类读取,但是当控件正在呈现时不应该向此类写入。
此类实现一个字典,可以像对待任何字典对象那样从其中添加或移除项。有关数据集合(如字典)的更多信息,请参见将数据组合到集合中。
[示例]
下面的示例说明一个具有 Text 和 FontSize 属性的复合 Label 控件。当在该控件上调用 Control.Render 方法时,这些属性保存到视图状态并从视图状态检索。
-------------------------------------------------------------------------------------------------------
[C#]
// This control renders values stored in view state for Text and FontSize properties.
using System;
using System.Web;
using System.Web.UI;
namespace ViewStateControlSamples {
public class Label: Control {
// Add property values to view state with set;
// retrieve them from view state with get.
public String Text {
get {
return (String) ViewState["Text"];
}
set {
ViewState["Text"] = value;
}
}
public int FontSize {
get {
return (int) ViewState["FontSize"];
}
set {
ViewState["FontSize"] = value;
}
}
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
protected override void Render(HtmlTextWriter output) {
output.Write("
1<font size=" + this.FontSize + ">" + this.Text + "</font>
");
}
}
}
---------------------------------------------------------------------------------------------
2.构造函数
2.1 StateBag 构造函数
public StateBag(); 初始化 StateBag 类的新实例。这是此类的默认构造函数。
public StateBag(bool); 初始化 StateBag 类的新实例,该实例允许存储的状态值不区分大小写。
忽略大小写为 true;否则为 false。
3.属性
3.1 StateBag.Count 属性
获取 StateBag 对象中的 StateItem 对象数。
属性值 是 StateBag 对象中的项数。
实现 ICollection.Count
使用示例:
-----------------------------------------------------
[C#]
private string GetMruList(string selectedValue) {
StateBag state = ViewState;
if (state.Count > 0) {
int upperBound = state.Count;
string[] keys = new string[upperBound];
StateItem[] values = new StateItem[upperBound];
state.Keys.CopyTo(keys, 0);
state.Values.CopyTo(values, 0);
StringBuilder options = new StringBuilder();
for(int i = 0; i < upperBound; i++) {
options.AppendFormat("
1<option value="{1}" {0}="">{2}", (selectedValue == keys[i])?"selected":"", keys[i], values[i].Value);
2}
3return options.ToString();
4}
5return "";
6}
7\----------------------------------------------------------------------------
83.2 StateBag.Item 属性
9获取或设置在 StateBag 对象中存储的项的值。
10[C#] 在 C# 中,该属性为 StateBag 类的索引器。
11属性值 是 StateBag 对象中的指定项。
12备注:使用该成员是为控件或页保存和检索视图状态值的最简单方法。
13如果在设置该属性时项尚未存储在 StateBag 对象中,则项的键/值对将添加到集合中。在项上调用 TrackViewState 方法之前,如果将该属性设置为空引用(Visual Basic 中为 Nothing),则项从 StateBag 对象中被移除。否则,当将该属性设置为空引用 (Nothing) 时,将保存键以便能够跟踪项的视图状态。
14示例:下面的示例说明一个将名称和值作为键/值对保存到 Control.ViewState 属性的属性。
15(Control.ViewState 属性是 StateBag 类的实例。)
16\---------------------------------------------------------------------------------
17[C#]
18// Add property values to view state with set;
19// retrieve them from view state with get.
20public String Text {
21get {
22return (String) ViewState["Text"];
23}
24set {
25ViewState["Text"] = value;
26}
27}
28\----------------------------------------------------------------------------------
293.3 StateBag.Keys 属性
30获取表示 StateBag 对象中的项的键集合。
31属性值 是 键集合。
32实现:IDictionary.Keys
33备注:这些键是控件属性的名称。例如,如果在自定义的 Table 控件上创建 BGColor 属性,则在此集合中将创建一个 BGColor 项来表示 Table 控件的那个属性。
34这些键与 StateBag 中为当前页或服务器控件存储的 StateItem 对象的名称相对应。
35可以使用 StateBag.GetEnumerator 方法循环访问该集合。
36
37[C#] 下面的示例说明如何使用 Keys 属性。
38\---------------------------------------------------------------------
39[C#]
40private string GetMruList(string selectedValue) {
41StateBag state = ViewState;
42if (state.Count > 0) {
43int upperBound = state.Count;
44string[] keys = new string[upperBound];
45StateItem[] values = new StateItem[upperBound];
46state.Keys.CopyTo(keys, 0);
47state.Values.CopyTo(values, 0);
48StringBuilder options = new StringBuilder();
49for(int i = 0; i < upperBound; i++) {
50options.AppendFormat("<option value="{1}" {0}="">{2}", (selectedValue == keys[i])?"selected":"", keys[i], values[i].Value);
51}
52return options.ToString();
53}
54return "";
55}
56\---------------------------------------------------------------------
573.4 StateBag.Values 属性
58获取存储在 StateBag 对象中的视图状态值的集合。
59属性值 是 视图状态值的集合。
60实现 :IDictionary.Values
61备注 :这是包含指定页或控件中的所有 StateItem 对象的值的集合。可以使用 StateBag.GetEnumerator 方法循环访问这些值。
62示例 :[C#] 下面的示例说明如何使用 Values 属性。
63\----------------------------------------------------------------------
64[C#]
65private string GetMruList(string selectedValue) {
66StateBag state = ViewState;
67if (state.Count > 0) {
68int upperBound = state.Count;
69string[] keys = new string[upperBound];
70StateItem[] values = new StateItem[upperBound];
71state.Keys.CopyTo(keys, 0);
72state.Values.CopyTo(values, 0);
73StringBuilder options = new StringBuilder();
74for(int i = 0; i < upperBound; i++) {
75options.AppendFormat("<option value="{1}" {0}="">{2}", (selectedValue == keys[i])?"selected":"", keys[i], values[i].Value);
76}
77return options.ToString();
78}
79return "";
80}
81\-----------------------------------------------------------------------
824.方法
834.1 StateBag.Add 方法
84[概述]将新的 StateItem 对象添加到 StateBag 对象。如果项已经存在于 StateBag 中,则它更新项的值。
85[调用形式][C#]
86public StateItem Add(
87string key,
88object value
89);
90[参数]
91key
92StateItem 对象的属性名称。
93value
94要添加到 StateBag 的项的值。
95[返回值]
96返回表示添加到视图状态的对象的 StateItem 对象。
97[异常]
98异常类型
99ArgumentException
100[条件]
101当 key 为空或 key 中的字符数为 0 时发生。
102[示例]
103[C#] 下面的示例说明如何使用 Add 方法。
104\-----------------------------------------------------------------------------------------------
105
106[C#]
107void GotoButton_Click(Object sender, EventArgs e) {
108InvoiceRecord invoice = GetInvoice(GotoId.Text);
109GotoId.Text = "";
110// Use the invoice Id as the key for the invoice
111// name in the StateBag.
112ViewState.Add(invoice.Id, invoice.Name);
113DisplayInvoice(invoice);
114selectedMruValue = invoice.Id;
115}
116
117\-----------------------------------------------------------------------------------------------
1184.2 StateBag.Clear 方法
119[概述]从当前 StateBag 对象中移除所有项。
120[调用形式]public virtual void Clear();
121[实现] IDictionary.Clear
122[示例]
123[C#] 下面的示例演示如何使用 Clear 方法
124\-------------------------------------------------------------------------------------------------
125
126[C#]
127// Implement the SaveViewState method. If the StateBag
128// that stores the MyItem class's view state contains
129// a value for the message property and if the value
130// has changed since the TrackViewState method was last
131// called, all view state for this class is deleted,
132// using the StateBag.Clear method,and the new value is added.
133object IStateManager.SaveViewState()
134{
135// Check whether the message property exists in
136// the ViewState property, and if it does, check
137// whether it has changed since the most recent
138// TrackViewState method call.
139if( (!((IDictionary)_viewstate).Contains("message")) || (_viewstate.IsItemDirty("message")))
140{
141{
142_viewstate.Clear();
143// Add the _message property to the StateBag.
144_viewstate.Add("message", _message);
145}
146}
147return ((IStateManager)_viewstate).SaveViewState();
148}
149\--------------------------------------------------------------------------------------------------
1504.3 StateBag.GetEnumerator 方法
151[概述]返回迭代 StateBag 中所存储的 StateItem 对象的所有键/值对的枚举数。
152[调用形式] public virtual IDictionaryEnumerator GetEnumerator();
153[ 返回值 ] 循环访问状态袋的枚举数。
154[实现] IDictionary.GetEnumerator
155[示例(C#)]
156\--------------------------------------------------------------------------------------------------
157[C#]
158// Create a StateBag object to contain the view state
159// associated with the custom control named myControl. Use the
160// StateBag.GetEnumerator method to create an
161// IDictionaryEnumerator named myDictionaryEnumerator.
162ctlViewState1 ctlOne = new ctlViewState1();
163StateBag myStateBag = new StateBag();
164myStateBag = ctlOne.GetState();
165IDictionaryEnumerator myDictionaryEnumerator = myStateBag.GetEnumerator();
166\-----------------------------------------------------------------------------------------------------
1674.4 StateBag.ICollection.CopyTo 方法
168[概述]该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
169[调用方法][C#]
170void ICollection.CopyTo(
171Array array,
172int index
173);
1744.5 StateBag.IDictionary.Add 方法
175[概述]该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
176[调用方法] [C#]
177void IDictionary.Add(
178object key,
179object value
180);
1814.6 StateBag.IDictionary.Contains 方法
182[概述]该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
183[调用方法][C#]
184bool IDictionary.Contains(
185object key
186);
1874.7 StateBag.IDictionary.Remove 方法
188[概述]该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
189[调用方法] [C#]
190void IDictionary.Remove(
191object key
192);
1934.8 StateBag.IEnumerable.GetEnumerator 方法
194[概述]该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
195[调用方法][C#]
196IEnumerator IEnumerable.GetEnumerator();
1974.9 StateBag.IsItemDirty 方法
198[概述]检查 StateBag 中存储的 StateItem 对象,计算自 Control.TrackViewState 调用后它是否已修改。
199[调用方法][C#]
200public bool IsItemDirty(
201string key
202);
203[参数]
204key
205要检查的项的键。
206[备注]
207如果 StateBag 中不存在键参数,此方法还返回 false。
208[示例][C#]
209下面的示例演示如何使用 IsItemDirty 方法。
210\--------------------------------------------------------------------------------------------
211[C#]
212// Implement the SaveViewState method. If the StateBag
213// that stores the MyItem class's view state contains
214// a value for the message property and if the value
215// has changed since the TrackViewState method was last
216// called, all view state for this class is deleted,
217// using the StateBag.Clear method,and the new value is added.
218object IStateManager.SaveViewState()
219{
220// Check whether the message property exists in
221// the ViewState property, and if it does, check
222// whether it has changed since the most recent
223// TrackViewState method call.
224if( (!((IDictionary)_viewstate).Contains("message")) || (_viewstate.IsItemDirty("message")))
225{
226{
227_viewstate.Clear();
228// Add the _message property to the StateBag.
229_viewstate.Add("message", _message);
230}
231}
232return ((IStateManager)_viewstate).SaveViewState();
233}
234\--------------------------------------------------------------------------------------------
2354.10 StateBag.IStateManager.LoadViewState 方法
236该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
237[调用方法][C#]
238void IStateManager.LoadViewState(
239object state
240);
2414.11 StateBag.IStateManager.SaveViewState 方法
242该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
243[调用方法][C#]
244object IStateManager.SaveViewState();
2454.12 StateBag.IStateManager.TrackViewState 方法
246该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
247[调用方法][C#]
248void IStateManager.TrackViewState();
2494.13 StateBag.Remove 方法
250[概述]将指定的密钥/值对从 StateBag 对象中移除。
251[调用方法][C#]
252public void Remove(
253string key
254);
255[参数]
256key
257要移除的项
258[示例][C#]
259下面的示例说明如何使用 Remove 方法。
260\--------------------------------------------------------------------------------------
261[C#]
262void MovePiece(string fromPosition, string toPosition) {
263StateBag bag = ViewState;
264object piece = bag[fromPosition];
265if (piece != null) {
266bag.Remove(fromPosition);
267bag.Add(toPosition, piece);
268RenderBoard();
269}
270else {
271throw new InvalidPositionException("There is no game piece at the \"from\" position.");
272}
273}
274\--------------------------------------------------------------------------------------
2754.14 StateBag.SetItemDirty 方法
276该成员支持 .NET Framework 结构,因此不适用于直接从代码中使用。
277[调用方法][C#]
278public void SetItemDirty(
279string key,
280bool dirty
281);
282
283***********************************************************************************************
284呵呵,是不是一个庞大的类?
285学习到这里,我们可以看到,StateBag的内部是一个一个的StateItem.现在我们就看一下这个庞然大物的一根根骨头吧.
286*********************************************************************************************
287
288.NET Framework 类库 StateItem 类
2891.类的信息
290[概述]表示当视图状态信息在 Web 请求间持续时保存在 StateBag 类中的项。无法继承此类。
291有关此类型所有成员的列表,请参阅 StateItem 成员。
292System.Object
293System.Web.UI.StateItem
294[类型][C#]
295public sealed class StateItem
296
297[线程安全]
298此类型的所有公共静态(Visual Basic 中为 Shared)成员是线程安全的。但不保证任何实例成员是线程安全的。
299
300[备注]
301视图状态是页或 ASP.NET 服务器控件属性值的累计,通过隐藏字段发送到请求浏览器。
302
303可以使用 Item 属性或 Add 方法,将 StateItem 对象显式添加到 ASP.NET 服务器控件的 StateBag。StateBag 然后跟踪它存储的所有项的更改。StateItem 对象的所有更改都反映在其 IsDirty 属性中。这些更改在服务器控件处理的保存视图状态阶段,刚好在控件呈现到页之前,通过 SaveViewState 方法调用进行保存。有关更多信息,请参见控件执行生命周期。
304
305[示例]
306[C#] 下面的示例使用 StateItem 类的 Value 和 IsDirty 属性保存简单的自定义 ASP.NET 服务器控件类 FirstCustomControl 的状态。在页发送到服务器后,IsDirty 属性检查项是否被修改过。该状态值可通过访问 Value 属性来显示。
307\------------------------------------------------------------------------------------------------------
308[C#]
309// Create a function that iterates through the view-state
310// values stored for this class and returns the
311// results as a string.
312public string EnumerateViewState()
313{
314string keyName,keyValue;
315string result = String.Empty;
316StateItem myStateItem;
317IDictionaryEnumerator myDictionaryEnumerator = _viewstate.GetEnumerator();
318while(myDictionaryEnumerator.MoveNext())
319{
320keyName = (string)myDictionaryEnumerator.Key;
321myStateItem = (StateItem)myDictionaryEnumerator.Value;
322keyValue = (string)myStateItem.Value;
323result = result + "<br/>ViewState[" + keyName + "] = " + keyValue;
324}
325return result;
326}
327\------------------------------------------------------------------------------------------------------
3282.属性
3292.1 StateItem.IsDirty 属性
330[概述]获取或设置一个值,该值指示 StateItem 对象是否已修改。
331[定义][C#]
332public bool IsDirty {get; set;}
333[属性值]
334如果存储的 StateItem 对象已修改,则为 true;否则为 false。
335
3362.2 StateItem.Value 属性
337[概述]获取或设置存储在 StateBag 对象中的 StateItem 对象的值。
338[定义] [C#]
339public object Value {get; set;}
340[属性值] 存储在 StateBag 对象中的 StateItem 的值。
341[示例] [C#]
342\--------------------------------------------------------------------------------
343// Create a function that iterates through the view-state
344// values stored for this class and returns the
345// results as a string.
346public string EnumerateViewState()
347{
348string keyName,keyValue;
349string result = String.Empty;
350StateItem myStateItem;
351IDictionaryEnumerator myDictionaryEnumerator = _viewstate.GetEnumerator();
352while(myDictionaryEnumerator.MoveNext())
353{
354keyName = (string)myDictionaryEnumerator.Key;
355myStateItem = (StateItem)myDictionaryEnumerator.Value;
356keyValue = (string)myStateItem.Value;
357result = result + "<br/>ViewState[" + keyName + "] = " + keyValue;
358}
359return result;
360}
361
362\----------------------------------------------------------------------------------
363**********************************************************************************
364ok,现在我们对ViewState的理解应该深入了很多,这对我们以后的编程很有好处哟 </option></option></option>