Control.SaveControlState 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將自頁面發布以來發生的任何伺服器控制狀態變更,都儲存回伺服器。
protected public:
virtual System::Object ^ SaveControlState();
protected internal virtual object SaveControlState();
abstract member SaveControlState : unit -> obj
override this.SaveControlState : unit -> obj
Protected Friend Overridable Function SaveControlState () As Object
傳回
回傳伺服器控制的當前狀態。 若控制項無狀態,則此方法回傳 null。
範例
以下程式碼範例覆蓋了自訂 ASP.NET 控制項中的 SaveControlState 方法。 當此方法被呼叫時,會判斷內部屬性 currentIndex 是否設定為非預設值,若是,則將該值儲存為控制狀態。
OnInit方法會被覆寫,以呼叫 RegisterRequiresControlState 上Page的方法,表示自訂控制使用控制狀態。
public class Sample : Control {
private int currentIndex = 0;
protected override void OnInit(EventArgs e) {
Page.RegisterRequiresControlState(this);
base.OnInit(e);
}
protected override object SaveControlState() {
return currentIndex != 0 ? (object)currentIndex : null;
}
protected override void LoadControlState(object state) {
if (state != null) {
currentIndex = (int)state;
}
}
}
Class Sample
Inherits Control
Dim currentIndex As Integer
Protected Overrides Sub OnInit(ByVal e As EventArgs)
Page.RegisterRequiresControlState(Me)
currentIndex = 0
MyBase.OnInit(e)
End Sub
Protected Overrides Function SaveControlState() As Object
If currentIndex <> 0 Then
Return CType(currentIndex, Object)
Else
Return Nothing
End If
End Function
Protected Overrides Sub LoadControlState(ByVal state As Object)
If (state <> Nothing) Then
currentIndex = CType(state, Integer)
End If
End Sub
End Class
備註
使用此 SaveControlState 方法儲存特定控制運作所需的狀態資訊。 這些控制狀態資料與控制項的檢視狀態資料分開儲存。
使用控制狀態的自訂控制必須在儲存控制狀態前呼叫該 RegisterRequiresControlState 方法 Page 。
給繼承者的注意事項
當控制狀態被儲存時,一個字串物件會以變數形式回傳給用戶端,並儲存在 HTML HIDDEN 元素中。 覆寫此方法以提取狀態資訊以供你控制。
控制狀態用於處理少量關鍵資料,例如頁面索引或關鍵字。 使用控制狀態處理大量資料可能會對頁面效能產生負面影響。 欲了解更多資訊,請參閱 ASP.NET 州管理概述。