在页面生命周期执行时 Page 对象在 SaveState 阶段都发生了什么事?

时间:2021-01-30 17:08:52

先看下 SaveViewState 的源码:

 // Answer any state this control or its descendants want to save on freeze.
// The format for saving is Triplet(myState, ArrayList childIDs, ArrayList childStates),
// where myState or childStates and childIDs may be null.
internal object SaveViewStateRecursive() {
if (flags[disableViewState])
return null; object adapterState = null;
if (_adapter != null) {
adapterState = _adapter.SaveAdapterViewState();
} object controlSavedState = SaveViewState(); ArrayList childStates = null;
if (HasControls()) {
ControlCollection occasionalFieldControls = _occasionalFields.Controls;
int occasionalFieldControlCount = occasionalFieldControls.Count; bool useId = LoadViewStateByID;
for (int i = ; i < occasionalFieldControlCount; i++) {
Control child = occasionalFieldControls[i];
object childState = child.SaveViewStateRecursive();
if (childState != null) {
if (childStates == null) {
childStates = new ArrayList(occasionalFieldControlCount);
} if (useId) {
child.EnsureID();
childStates.Add(child.ID);
}
else {
childStates.Add(i);
}
childStates.Add(childState);
}
}
} if (_adapter != null) {
if ((controlSavedState != null) || (adapterState != null) || (childStates != null)) {
return new Triplet(controlSavedState, adapterState, childStates);
}
}
else {
if ((controlSavedState != null) || (childStates != null)) {
return new Pair(controlSavedState, childStates);
}
} return null;
}

SaveViewState

从上面的源码可以看出当页面运行至 SaveState 阶段时,将调用其自身 SaveAllState() 方法,在这个方法内部,做了两件事,第一件事就是保存控件状态,即ControlState,第二件事就是保存控件视图状态,即ViewState。ControlState我们放到以后再说,今天说说ViewState,在SaveAllState()这个方法内部,调用控件的SaveViewStateRecursive()方法,在这个方法的内部,调用控件的SaveViewState方法

页面到 SaveState 阶段时,会调用自身 SaveAllState() 方法并且在这个方法内部执行两个动作:保存控件状态 (ControlState) 和保存控件视图状态 (ViewState) 。 ControlState 等后面有时间再跟大家分享下,今天主要聊下 ViewState ,在 SaveAllState() 这个方法内部调用控件的 SaveViewStateRecursive() 方法,并且在这个方法内部再去调用 SaveViewState 方法。

Line 5:比较值得注意,平常在设置 ASP.NET 前台页面会经常去接触 EnableViewState 属性,而 flags[disableViewState] 是与 EnableViewState  相对应的。从这里是不是已经 get 到什么了呢?

if (flags[disableViewState])

最后简单写个示例,来看看页面是如何递归保存其内部控件的视图状态:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Xudaxia.ViewState.Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

上面这个结构就不多说了,来看看这个页面对应的控件树:

在页面生命周期执行时 Page 对象在 SaveState 阶段都发生了什么事?