Choose a location:
Download the sample application
In ASP.NET there are a number of options available for state management. You choose the right option depending on-
The data you need to store.
The length of time you want to store it.
The scope of your data (whether it’s limited to individual users or shared across multiple requests)
Additional security and performance considerations.
The different types of state management options in ASP.NET are complementary, which means you’ll almost always use acombination of them in the same web application (and often the same page).
ASP.NET view state is the client side state management technique used by an ASP.NET Web page to persist changes to the state of a Web Form across post backs. Data can be added to the view state collection using a build-in-property called ViewState. The type of information that can be stored to the view state includes simple data types and custom Objects. ASP.NET view state relies on a dictionary collection, where each item is indexed with a unique string name.
Some facts about view state are tabulated below-
Control state is another type client site state management technique which is basically a private view state for a control. To preserve the page and control data over round trips to the web server, conventionally we use view state. But If you disable the view state in your page, the custom controls used in your page has a chance of losing their state. To resolve this problem ASP.NET 2.0 has introduced Control State, private view state for the control, and preserves the state of the control even when you turn off the View State. But note that Control State Cannot be disabled. Control state should only be used for small amounts of critical data that are essential for the control across post backs. Control state mustn't be used as an alternative to view state.
Location of ControlStateBy default, the ASP.NET stores control state in the same hidden field in which it stores view state. Even if view state is disabled, or when state is managed using Session, control state moves to the client and back to the server in the page. On post back, ASP.NET desterilizes the contents of the hidden element and loads control state into each control that is registered for control state.
Location of ViewStateThe view state of a page is, by default, placed in a hidden form field named __VIEWSTATE as a single Base64-encoded string (A Base64 string ensures that there aren’t any special characters that wouldn’t be valid HTML.) that looks like this-
The view state string isn’t human readable—it just looks like a series of random characters. But note that it is not an encrypted string. It can easily bedecoded. So view state isn’t a good place to store sensitive information. Be careful about it.
ViewState vs ControlState
Data can be store into view state in following manner –
Above the values 18 and tom have been placed into the ViewState collection and gives these the descriptive names AGE and NAME. If there are currently no items with the names AGE and NAME, new items will be added automatically. If there are already items indexed under the names AGE and NAME, these will be replaced.
These values can easily be retrieved by using key names. But retrieved values should be cast to the appropriate data types. This required as by default the ViewState collection casts all items to the base Object type.
If attempted value that isn’t present in the collection, you’ll receive a NullReferenceException. To handle this possibility, check for a null value should be performed before an attempt to retrieve and cast data that might not be present.
Objects can be stored in view state just like numeric and string types. However, objects must be serializable otherwise you’ll receive an error message when you attempt to place them in view state. E.g. consider an object Employee
If you will try to store this object in the ViewState, you will face following error-
In order to store employee object in the ViewState you must be make it serializable by adding Serializable attribute before Employee class declaration as-
Now you can store Employee object in the ViewState as-
Ant can be retrieve from view state as –
Note that to be serializable, your classes you must meet these requirements:
When to use ViewStateIn the following cases can be used –
When to not use ViewState In the following cases it should be avoided –
Advantages of using ViewState
Below are the advantages of using view state-
Disadvantages of using ViewStateBelow are the disadvantages of using view state-
Profiling the ViewState usage of a page
The amount of space used by view state depends on the number of controls, their complexity, and the amount of dynamic information. If you want to profile the view state usage of a page, simply turn on tracing by adding the Trace attribute to the Page directive as-
See the Control Tree section. Although it doesn’t provide the total view state used by the page,but it does indicate the view state used by each individual control in the Viewstate Size Bytes column (see Figure below). Don’t worry about the Render Size Bytes column, which simply reflects the size of the rendered HTML for the control.
Enabling / Disabling ViewStateYou can enable/disable view state for a single control or for a whole page. To turn off/on view state for an entire page and all its controls, set the EnableViewState property of the page to false/true, or use the EnableViewState attribute in the Page directive as -
To turn off/on view state for a control, set the EnableViewState property of the control to false/true -
To improve the transmission times of page, it will be a good idea to eliminate view state when it’s not required. It makes the sense to disable it on a per-control basis.
Although the size of the hidden view state field has no limit, however, some proxy servers and firewalls don’t allow pages having hidden fields greater than a certain size. To avoid this problem, you can use view state chunking, which automatically divides view state into multiple fields to ensure that no hidden field exceeds a size threshold you set. To use view state chunking, you simply need to set the maxPageStateFieldLength attribute of the <pages> element in the web.config file. This specifies the maximum view state size, in bytes. Here’s an example that caps view state at 1 KB:
When you request a page that generates a view state larger than this, several hidden input fields will be created:
Remember, view state chunking is simply a mechanism for avoiding problems with certain proxies and it does not improve performance. Actually it adds a small amount of extra serialization overhead. ViewState Security As I’ve already explained that view state is a single Base64-encoded string. It isn’t human readable but it doesn’t mean it is encrypted. It can easily be examined using reverse – engineering. In order to secure view state, there are two options –
Using a hash code to tamper-proof view state information.
Using view state encryption.
A hash code is a cryptographically strong checksum and ASP.NET calculates this checksum based on the content of the current view state and adds it to the hidden field when it returns the page. When the page is posted back, ASP.NET recalculates the checksum and if it doesn’t match then it means that a malicious user has changed the view state data and ASP.NET will be able to detect the change, and it will reject the post back, and if both the checksums match, then ASP.NET will accept the post back.
Hash codes are enabled by default and need not to take any extra steps. But hash code creates problems in case of web farms as different servers have different keys. The problem occurs if the page is posted back and handled by a new server. In this case new server won’t be able to verify the view state information. So in this case it would become necessary to disable this feature.Hash codes can be disabled by using EnableViewStateMAC (here MAC stand for machine authentication check) property of the Page directive in.aspx file as:
Otherwise, you can set the enableViewStateMac attribute of the <pages> element in the web.config or machine.config file for the whole as:
Even if you are using hash codes, the view state data is still readable. You can prevent users from viewing view state data by using view state encryption. You can turn on view state encryption for an individual page by using the ViewStateEncryptionMode property of the Page directive as:
There are three choices for view state encryption setting:
Otherwise , you can set the same attribute in the web.config configuration file for the whole site:
• Always - always encrypt. • Never - never encrypt.• Auto - encrypt only if a control specifically requests it.
The default value of viewStateEncryptionMode is Auto, which means that the page won’t encrypt its view state unless a control on that page specifically requests it. To request encryption, a control must call the Page.RegisterRequiresViewStateEncryption method. Note that view state encryption has extra encryption overhead. However, the control doesn’t have absolute power—if it calls Page.RegisterRequiresViewStateEncryption and the encryption mode of the page is Never, the view state won’t be encrypted.
The viewstate does a lot of work in saving the state of controls. However it comes with a cost. If a page contains a lot of controls holding a large amount of data, then there will be huge load when this data is transferred to and from the browser on each post back. It gradually increases the size of page, thus leading to performance issues. you can handle this situation by disabling viewstate for controls, where maintaining state is not required (EnableViewState=false). Nevertheless, in scenarios, where maintaining the state of controls is required, you can compress viewstate in order to improve performance.
In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.Simply create a BasePage class inherited from the System.Web.UI.Page class, and use this class as the base class utilizes ViewState compression for all web pages of your web application. This BasePage class adds an additional hidden field _COMPRESSEDVIEWSTATE, to store the compressed ViewState.
Where Compress and Decompress are static methods of the class VSCompression
If you view the page HTML with viewstate compression, you find that the __VIEWSTATE field is empty, whereas __COMPRESSEDVIEWSTATE field contains the compressed Base64 encoded ViewState. View state compression reduces the size of the viewstate by 40 - 60% but compression, decompressing, encoding and decoding data is a extra overload on the server. It saves the bandwidth but offers shorter response times for users.
Where to Persist the ViewState
As soon as the page has collected the view state information for all of the controls in its control hierarchy in the save view state stage, it persists it to the __VIEWSTATE hidden form field. The view state is serialized to the hidden form field in the Page class's SavePageStateToPersistenceMedium method during the save view state stage, and is deserialized by the Page class's LoadPageStateFromPersistenceMedium method in the load view state stage. But view state can be persisted to the Web server's file system, rather than as a hidden form field weighing down the page. To accomplish this we'll need to create a class that derives from the Page class and overrides the SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium methods.The view state is serialized and deserialized by the System.Web.UI.LosFormatter class—the LOS stands for limited object serialization—and is designed to efficiently serialize certain types of objects into a base-64 encoded string. The LosFormatter can serialize any type of object that can be serialized by the BinaryFormatter class, but is built to efficiently serialize objects of the following types:
• Strings • Integers • Booleans • Arrays • ArrayLists • Hashtables • Pairs • TripletsNote that the Pair and Triplet are two classes found in the System.Web.UI namespace, and provide a single class to store either two or three objects. The Pair class has properties First and Second to access its two elements, while Triplet has First, Second, and Third as properties.
Participating a control in ControlState
The following 3 - steps must be followed in order to enable a control to participate in control state:
Here I've described briefly about view state and control state. I’ve tried to explain from very basic level to advanced level and included some advanced topics about view state and control state concisely. Hope all of like this article.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?