Control.ViewState 属性


获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原服务器控件的视图状态。Gets a dictionary of state information that allows you to save and restore the view state of a server control across multiple requests for the same page.

 virtual property System::Web::UI::StateBag ^ ViewState { System::Web::UI::StateBag ^ get(); };
protected virtual System.Web.UI.StateBag ViewState { get; }
member this.ViewState : System.Web.UI.StateBag
Protected Overridable ReadOnly Property ViewState As StateBag


包含服务器控件视图状态信息的 StateBag 类的实例。An instance of the StateBag class that contains the server control's view-state information.



下面的示例演示如何实现一个 Text 属性,该属性从其控件的 ViewState 属性存储和检索其值。The following example demonstrates implementing a Text property that stores and retrieves its value from its control's ViewState property.

// Add property values to view state with set;
// retrieve them from view state with get.
public String Text
        object o = ViewState["Text"]; 
        return (o == null)? String.Empty : (string)o;

        ViewState["Text"] = value;

' Add property values to view state with set; 
' retrieve them from view state with get.
Public Property [Text]() As String
        Dim o As Object = ViewState("Text")
        If (IsNothing(o)) Then
            Return String.Empty
            Return CStr(o)
        End If
    End Get
    Set(ByVal value As String)
        ViewState("Text") = value
    End Set
End Property


服务器控件的视图状态是其所有属性值的累计。A server control's view state is the accumulation of all its property values. 为了跨 HTTP 请求保留这些值,ASP.NET 服务器控件使用此属性(StateBag 类的实例)来存储属性值。In order to preserve these values across HTTP requests, ASP.NET server controls use this property, which is an instance of the StateBag class, to store the property values. 然后,在处理后续请求时,这些值将作为变量传递给 HTML 隐藏输入元素。The values are then passed as a variable to an HTML hidden input element when subsequent requests are processed. 有关保存服务器控件视图状态的详细信息,请参阅ASP.NET 状态管理概述For more information about saving server control view state, see ASP.NET State Management Overview.

默认情况下,将为所有服务器控件启用视图状态,但在某些情况下,你将需要禁用该状态。View state is enabled for all server controls by default, but there are circumstances in which you will want to disable it. 有关详细信息,请参阅ASP.NET 性能概述For more information, see ASP.NET Performance Overview.

有关字典以及如何使用它们的信息,请参阅集合和数据结构For information about dictionaries and how to use them, see Collections and Data Structures.