ViewState: all you wanded to know

zhaozj2021-02-11  169

ViewState: all you wanded to know

Paul Wilson

Www.wilsondotnet.com

Www.aspalliance.com/paulwilson

Previous Article Page Events and Postback Next Article

What ViewState is NotFirst, lets consider what ViewState is NOT, since there are several common misconceptions. ViewState does not help restore posted values ​​to form controls, although this is said at times. The easiest way to see this is to disable a controls ViewState and watch its value be restored. This is done automatically for us by matching the posted form variable name with the control, although this only works for controls that are created by the time the Load event is completed. So while ASP.NET does automate the restoring Of form values, this is not part of viewstate.

ViewState also does not auto-recreate any controls that were dynamically created in the code. This is actually something that many of us have discovered the hard way, since it doesnt work. Any controls that you dynamically create in your code must therefore be recreated in the code. This can be a little difficult at times to work around, especially for controls created in events, but it is doable if you keep track of whats been previously done and recreate it on each Load. ViewState can, however, be used to TRACK THIS INFORMATION, But Weme Must Manually Code for IT.

Finally, ViewState is not intended for user or session data, nor for transferring across pages. ViewState is only designed for state data related to the current page and its various controls. It does not get sent to a new page in any case, not through links, redirects, or server transfers. There may be things that you want to access on multiple pages, due to redirects or transfers, but the solutions involve using either cookies, session, or the request context, not ViewState. We will also see that ViewState is neither secure, nor always the best use of server resources.So What is ViewStateViewState is used to track and restore the state values ​​of controls that would otherwise be lost, either because those values ​​do not post with the form or because they are not in the page html. This means that a control totally defined in your page html, with no changes made in the code, will have no ViewState at all, as is often the case when using drag-n-drop with static content. Instead, ViewState Only Holds The Values ​​of Properties That Are Dynamically Changed Somehow, USUALLY IN CODE, DATA-BINDING, OR USER INTERACTIONS, SO That The Can Be Restore on Each Request.

So, ViewState holds properties you change in code, any data that you bind to a control in code, and any changes that occur as a result of user interactions that were triggered with a PostBack. An example of a user interaction is a user selecting a date or moving a month in the calendar, which triggers a PostBack that changes properties of the calendar to match the users request. The new date selected or month being viewed must be persisted in the calendars ViewState since these are properties that will need to be restored But Which Will Not Be Posted Next Time.

ViewState also provides a StateBag, which is a special collection or dictionary, for each page that you can use to store any object or value, associated with a key, to retain across PostBacks. This is useful for your own custom items that are relevant to only that specific page instance, since these values ​​will automatically post with that page, but not transfer to any other pages. One very good use of custom ViewState is to keep track of any dynamically created controls, which you can then manually recreate on each post based on your tracking data in ViewState.And What is the FormatViewState is by default serialized and passed across page postBacks as a hidden form field, __VIEWSTATE, that is Base64 encoded so that it is not easily readable, but not encrypted. ViewState is by default Tamper-Proof, However, Since a Hash Is Applied Based on Machine Key, Alth this Is Disabled by Setting The EnableViewStateMac Property to False

See Listing 1). ViewState Can Be Optionally Encrypted, by Setting Up MachineKey Validation

SEE LISTING 2), But this Must Be Done At the Machine Level and IT Uses More Resources So Its Not Recommended.

ViewState is saved before rendering in the Page.SavePageStateToPersistenceMedium method and it is restored on PostBacks in the Page.LoadPageStateFromPersistenceMedium method. Both of these methods can be easily overridden to save ViewState to Session (see Listing 3), which is useful for low-bandwidth cases, like Mobile devices which use Session by default. Storing the ViewState in other data stores, like a database or even advanced Session modes, requires serialization and deserialization using the special LosFormatter class (see Listing 4).

Finally, lets take a look at the internal format of the ViewState object for completeness sake. Each controls ViewState is stored in a Triplet (System.Web.UI.Triplet) with the First object being a Pair (System.Web.UI.Pair ), or Array or Pairs, of ArrayLists of related name-values. The Second object of the Triplet is an ArrayList of that controls child indices in control tree, and the Third object is an ArrayList of the similar associated Triplets of those child controls. ITS All Rather Hard to Describe, So Look At The Example and try it for yourself (see Listings 5/6) .listing 1: ViewState Machine Hash Disabled

Machine.config or Web.config:

Page Level Directive: <% @ Page EnableViewStateMac = 'false'%>

Page Level Script Code: Page.enableViewStateMac = False;

Listing 2: ViewState Encryption is enabled

Machine.config:

WHERE The ValidationKey Must Be The Same Across A WEB-FARM SETUP

Also Requires The EnableViewStatemac Property Setting To Be True

Listing 3: ViewState Saved in Session State

Protected Override Object loadingPagestateFromPersistencemedium () {

Return session ["ViewState"];

}

Protected Override Void SavepageStateTopersistencemedium (Object ViewState) {

Session ["ViewState"] = viewState;

// bug Requires Hidden Field __ViewState

Registerhiddenfield ("__viewstate", "");

}

Listing 4: ViewState Saved In Custom Store

Protected Override Object loadingPagestateFromPersistencemedium () {

Losformatter Format = new losformatter ();

Return format.deSerialize (YourDataStore ");

}

Protected Override Void SavepageStatetopersistenceMedium (Object ViewState) {Losformatter Format = New Losformatter ();

StringWriter Writer = new stringwriter ();

Format.Serialize (Writer, ViewState);

YourDataStore ["ViewState"] = Writer.toString ();

}

Listing 5: ViewState Decode / Parse EXAMPLE

Encoded ViewState:

DDWXMJM0NTY3ODKWO3Q8CDXSPHBYCEE7CHJWQJTWCNBDOZ47BDX2YWXBO3ZHBEI7DMFSQZS PJTSPGK8

MD47ATWYPJTPPDM O2K8NT47PJTSPHQ8CDXSPHBYCEE7CHJWQJS O2W8DMFSQTTT2YWXCOZ4 OZS O3Q8

CDXSPHBYCEE7CHJWQJS O2W8DMFSQTTTT2YWXCOZ4 OZS O3Q8cDxsphbycee7chjwqjs O2W8DMFSQTT2

YWXCOZ4 OZS O3Q8CDXSPHBYCEE7CHJWQJS O2W8DMFSQTT2YWXCOZ4 OZS OZ4 OZ4 =

Decoded ViewState:

T

; l >;

L ; i <2>; i <3>; i <5>;>; l <

T

; l > ;;

T

; l > ;;

T

; l > ;;

T

; l > ;;>; >>;>

PARSED ViewState:

T <1234567890; Page-Level Triplet IS Special Case

T

; triplet-first: pair-first: arraylist

L Pair-Second: ArrayList

"

L ; Triplet-Second: ArrayList: INDICES

i <2>; of the

i <3>; Children

I <5>; Controls

"

L

; triplet-third: arraylist: Triplets

L of the

CHILDREN; Controls

"

T

; Each Sub-Triplet Follows Same Pattern

l >>>>

"

More Levels Possible if Sub-Children

"

T

; Each Sub-Triplet Follows Same Pattern

l >>>>

"

More Levels Possible if Sub-Children

"

T

; Each Sub-Triplet Follows Same Pattern

l >>>>

"

More Levels Possible if Sub-Children

"

>

>; Closing of Special Page-Level Triplet

>

Listing 6: ViewState Decode / Parse Code

Protected Override Void SavepageStateTopersistencemedium (Object ViewState) {

// Call Base Method to Not Change Normal Process

Base.savepagestatetopersistencemedium (ViewState);

// Retrieve ViewState and Write Out to Page

Losformatter Format = new losformatter ();

StringWriter Writer = new stringwriter ();

Format.Serialize (Writer, ViewState);

String vsraw = Writer.toTString ();

Response.write ("ViewState Raw: Server.htmlencode (vsraw));

// Decode ViewState and Write Out to Page

Byte [] buffer = convert.frombase64string (vsraw);

String vStext = Encoding.ascii.getstring (buffer);

Response.write ("ViewState Text: Server.htmlencode (vStext));

// Parse ViewState - Turn on Page Tracing

ParseViewState (ViewState, 0);

}

Private void ParseViewState (Object vs, int level) {

IF (vs == null) {

Trace.warn (Level.Tostring (), Spaces (Level) "NULL");

}

Else IF (vs.gettype () == typeof (system.web.ui.triplet) {

Trace.warn (Level.Tostring (), Spaces (Level) "Triplet"); PARSEVIEWSTATE ((Triplet) vs, level;

}

Else IF (vs.gettype () == typeof (system.Web.ui.pair) {

Trace.warn (Level.Tostring (), Spaces (Level) "Pair");

PARSEVIEWSTATE ((Pair) VS, Level);

}

Else IF (vs.gettype () == typeof (system.collections.arraylist) {

Trace.warn (Level.Tostring (), Spaces (Level) "ArrayList");

PARSEVIEWSTATE ((ienumerable) vs, level;

}

ELSE IF (vs.gettype (). isarray) {

Trace.warn (Level.Tostring (), Spaces (Level) "Array");

PARSEVIEWSTATE ((ienumerable) vs, level;

}

Else IF (vs.gettype () == typeof (system.string)) {

TRACE.WARN (Level.Tostring (), Spaces (Level) "'" vs.tostring () "'");

}

Else IF (vs.gettype (). isprimitive) {

Trace.warn (Level.Tostring (), Spaces (Level) vs.tostring ());

}

Else {

Level.Warn (Level.Tostring (), Spaces (Level) vs.gettype (). TOSTRING ());

}

}

Private void ParseViewState (Triplet vs, int level) {

ParseViewState (vs.first, level 1);

ParseViewState (vs.second, level 1);

ParseViewState (vs.third, level 1);

}

Private void ParseViewState (Pair vs, int level) {

ParseViewState (vs.first, level 1);

ParseViewState (vs.second, level 1);

}

Private void ParseViewState (IEnumerable VS, INT Level) {

Foreach (Object Item IN vs) {

PARSEVIEWSTATE (Item, Level 1);

}

}

Private string spaces (int count) {

String spaces = "";

For (int index = 0; index

Spaces = "";

}

Return Spaces;

}

Author BioPaul Wilson is a software architect in Atlanta, currently with a medical device company. He specializes in Microsoft technologies, including .NET, C #, ASP, SQL, COM , and VB. HisWilsonWebForm Control allows Multiple Forms and Non-PostBack Forms in ASP .NET. HE IS A Microsoft MVP in Asp.Net and Is Also Recognized as an aspfriend's

Aspace / aspelite. He is a moderator on Microsoft's

Asp.net forums, as well as one of the top posters. He is certified in .NET (MCAD), AS Well As Also Holding The MCSD, MCDBA, And McSE. Please Visit His Website,

Www.wilsondotnet.com, or Email Him At

Paul@wilsondotnet.com.

转载请注明原文地址:https://www.9cbs.com/read-5347.html

New Post(0)