ASP. NET status management (view status viewstate)

Source: Internet
Author: User
Tags object serialization
ArticleDirectory
    • View status
    • View status example
    • Save objects in view status
    • View Status Evaluation
    • Disabled view status selected
    • View status security

Regardless of the webProgramThe framework is so advanced that it cannot change the fact that:HTTP is a stateless protocol..

After each Web request, the client and server are disconnected and the ASP. NET engine releases the Page Object. This architecture ensures that Web applications can respond to thousands of concurrent requests simultaneously without causing server memory crashes. However, the negative effect is that you must use other technologies to store information between Web requests and obtain them as needed.

 

View status

View status is the first option to save information on a single page.. The ASP. NET web control also uses the attempt state to save the attribute value between sending and sending.Use the built-in viewstate attribute on the page, You can put your data into the view status set,Information types that can be saved include simple data types and custom objects..

Similar to most state management in ASP. NET, view States depend on dictionary sets. Each item in the collection is indexed by a unique string name.

Viewstate ["counter"] = 1;

If there is no counter index in the collection, it will be automatically added.

If it already exists, it will be replaced.

Viewstate reads values by using key values. Because different data types need to be processed, viewstate saves all data as the object type. Therefore, data type conversion is involved in use.

Int count;

If (vietstate ["count"]! = NULL)

{

Count = (INT) viewstate ["count"];

}

If you try to find a value that does not exist in a set, an nullreferenceexception exception is returned. Therefore, you need to perform the null determination operation.

 

View status example

The followingCodeDemonstrate how to use view status on a page. It allows you to save a series of values and restore them. This Code uses recursion to traverse all child controls. Because the Control ID is unique on the page, it is used as the key value of the view State.

Public Partial ClassChapter06_viewstatetest: system. Web. UI. Page

 
{

 
Protected VoidBtnsave_click (ObjectSender, eventargs E)

 
{

 
Savealltext (This. Table1.controls,True);

 
}

 
 

Protected VoidBtnrestore_click (ObjectSender, eventargs E)

 
{

 
Restorealltext (This. Table1.controls,True);

 
}

 
 

 
Private VoidSavealltext (controlcollection controls,BoolSavenested)

 
{

Foreach(ControlInControls)

 
{

 
If(ControlIsTextbox)

 
{

 
Viewstate [control. ID] = (textbox) control). text;

 
}

 
 

 
// The savenested parameter of the bool type provides more flexibility for the method.

 
// You can determine whether recursion is required.

 
If(Control. controls! =Null& Savenested)

 
{

 
Savealltext (control. controls,True);

 
}

 
}

 
}

 
 

 
Private VoidRestorealltext (controlcollection controls,BoolSavenested)

 
{

 
Foreach(ControlInControls)

 
{

 
If(ControlIsTextbox)

 
{

 
If(Viewstate [control. ID]! =Null)

 
{

 
(Textbox) control). Text = viewstate [control. ID]. tostring ();

 
}

}

 
 

 
If(Control. controls! =Null& Savenested)

 
{

 
Restorealltext (control. controls,True);

 
}

 
}

 
}

 
}

 

Save objects in view status

When saving a project in view State, ASP. NET needs to convert it to a bit stream to add it to a hidden field on the page. This process is called serialization..

Objects cannot be serialized by default. A view saves an object that cannot be serialized to the view State and generates an error message to enable Object serialization, the serializable attribute must be added before the class declaration..

 
// Indicates that a class can be serialized.

 
[Serializable]

 
Public ClassCustomer

 
{

 
Public StringFirstname;

Public StringLastname;

 
 

 
PublicCustomer (StringFirstname,StringLastname)

 
{

 
Firstname = firstname;

 
Lastname = lastname;

 
}

 
}

Because the customer class is now marked as serializable, it can be stored in the view State:

Customer Cust =NewCustomer ("Malia","Carry");

 
Viewstate ["Currentcustomer"] = Cust;

You can also read custom objects from them:

 
Customer Cust;

 
If(Viewstate ["Currentcustomer"]! =Null)

 
{

 
Cust = (customer) viewstate ["Currentcustomer"];

 
}

 

 

To make the class serializable, it must meet the following conditions:

    1. Class must have the serializable feature.
    2. Any of its base classes must have the serializable feature.
    3. All member variables must be serializable data types. Otherwise, all non-serialized data must be identified as nonserialized, which will be ignored.

Example:

 
Public Partial ClassChapter06_viewstatetest: system. Web. UI. Page

 
{

 
Protected VoidBtnsave_click (ObjectSender, eventargs E)

 
{

 
Dictionary <String,String> Dict =NewDictionary <String,String> ();

 
Savealltext (This. Table1.controls, dict,True);

 
Viewstate ["Controltext"] = Dict;

 
}

 
 

Protected VoidBtnrestore_click (ObjectSender, eventargs E)

 
{

 
If(Viewstate ["Controltext"]! =Null)

 
{

 
Dictionary <String,String> Dict

= Viewstate ["Controltext"]AsDictionary <String,String>;

 
 

 
// Keyvaluepair defines key/value pairs that can be set or retrieved.

 
Foreach(Keyvaluepair <String,String> ItemInDict)

 
{

Label1.text + = item. Key +"="+ Item. Value +"<Br/>";

 
}

 
}

 
}

 
 

 
Private VoidSavealltext (controlcollection controls, Dictionary <String,String> Dict,BoolSavenested)

 
{

Foreach(ControlInControls)

 
{

 
If(ControlIsTextbox)

 
{

 
Dict. Add (control. ID, (textbox) control). Text );

 
}

 
If(Control. controls! =Null& Savenested)

 
{

Savealltext (control. Controls, dict,True);

 
}

 
}

 
}

 
}

Effect:

 

View Status Evaluation

View status is an ideal way to manage the status, because it neither consumes server memory nor imposes additional restrictions (such as timeout ). Why does it force you to discard the view status and use other State management methods? There are three possible reasons:

    1. Core Business data needs to be stored, which cannot be tampered with by users. (Smart users may modify view status information in the return request)
    2. You need to save the information used by multiple pages. (In this case, session Status, cookie, and query string are considered)
    3. The amount of information to be stored is very large and it is not expected to affect the page transfer time. (In this case, consider using the database or session Status)

 

Disabled view status selected

Reducing unnecessary view states is a good way to reduce the page transfer time. In the following two cases, you do not need to use the view State of the control:

    1. Controls never change (for example, a button with static text does not need to use view status)
    2. Controls are refilled in each return

After setting the enableviewstate attribute of a control to false, you can disable its view State. After setting the enableviewstate of the page to false, you can disable the view State of the entire page and all its controls.(Set the enableviewstate feature in the page command to achieve the same effect ). You can also set the enableviewstate attribute of the <pages> element to false in the web. config file to disable the view State of all pages of the website.

 

You can disable the view status of a page, but explicitly use the view status of a specific control to overwrite page settings.! This new technology room ASP. Net 4 is particularly popular with developers who are eager to minimize the page view status. To achieve this goal, another attribute called viewstatemode is required.

Viewstatemode can be applied to all controls and pages with the following values:

    1. Enable: As long as the enableviewstate attribute enables the view state, the view State can work.
    2. Disabled: The view status of the control does not work, but the sub-control of the control can overwrite this value.
    3. Inherit: Controls inherit the viewstatemode value of the control's container. (Default)

To select the view state, you can set viewstatemode to disabled to disable the view state. You need to use the view state control to set this attribute to enable. Please note that we have not set enableviewstate to false. If so, ASP. NET will completely disable the view State of the page, and no control can be used again..

This model is a bit clumsy, but it does work when the size of the view State is a problem. The only drawback is that you must remember to explicitly use the view State for controls with dynamic values that require persistence or controls that must depend on the view State to work correctly.

 

View status security

<Input type = "hidden" name = "_ viewstate" id = "_ viewstate" value = "fakivy3d8tjpx6spp/o260nau17ykr"/>

View status information is saved as a single base64 encoded string. Because these values are not formatted as plain text, many ASP. net programmers mistakenly think that their view status data is encrypted, but this is not the case. Malicious users can reverse design this string within several seconds to find your view status data.

There are two ways to make the view status more secure:

    1. Hash code is used to ensure that view status information is not tampered with (hash code is a strong verification code ).
    2. Enable view State Encryption

Note 1:

Hash code is enabled by default. You do not need to make any additional settings.

NOTE 2:

Enabling encryption can be set in the page instruction or in the web. config file

<% @ Page viewstateencryptionmode = "always"/>

<Pages viewstateencryptionmode = "always"/>

 

Encryption Settings have three options:

    1. Always: Always encrypted
    2. Never: Never encrypted
    3. Auto: Always encrypt the control when required (default option)

WhenWhen the control requires encryption, it will callPage. registerrequiresviewstateencryption() Method to enable encryption. However, the control has no absolute control. If the page encryption mode is never, the control will not function even if the encryption method is called..

 

Do not encrypt view status data if not necessary. Encryption will cause performance degradation because the Web server needs to encrypt and decrypt each time it returns.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.