Loading ...

Viewstate and Controlstate in ASP.NET | CodeAsp.Net

Viewstate and Controlstate in ASP.NET

  • 0
    /5
    Avg: 0/5: (0votes)
  • (8)
  • (5421)
Published: 4/29/2010 by Samir NIGAM

 Download the sample application

 Introduction

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 a
combination of them in the same web application (and often the same page).

ViewState

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-

 View State
Allowed data typesAll serializable .NET data types.
Storage locationA hidden field in the current web page.
LifetimeRetained permanently for post backs to a single page.
ScopeLimited to the current page.
SecurityTamper-proof by default but easy to read. You can use the Page directive to enforce encryption.
Performance implicationsStoring a large amount of information will slow transmission but
will not affect server performance.
Typical usePage-specific settings.

 

 


 


 


 
ControlState

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 ControlState

By default, the ASP.NET stores co
ntrol 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 ViewState

The 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-

 Location of ViewState

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

ViewStateControlState
ViewState is client side state management technique used to persist changes to the state of a Web Form across post backs.Controlstate is also a client site state management technique which is
basically a private view state for a control.
It can be disabled.It cann't be disabled.
It can store large amount of data.It is only for small amounts of critical data essential for the control across postbacks.  

ViewState vs HiddenField

HiddenFieldViewState
It can be shared between two pages on client side using JavaScript.It can ce shared between two pages through Cross Page Posting.
It can only store string value.It can store string value as well as object (serialized ).
Data isn't secure.Data is much more secure than hiddenField.
It stores data as a plane text.It stores data as a single Base64-encoded string.
It has better performance than ViewState in case of large amount of data. Performance decreases than HiddenField in case of large amount of data.

 

 

 



Storing / Retrieving data into / from ViewState

Data can be store into view state in following manner –

Storing-Retrieving

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.

Storing-Retrieving

 
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.

Storing / Retrieving Objects into / from ViewState

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

  Storing-Retrieving-Objects

If you will try to store this object in the ViewState, you will face following error-

 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-

Storing-Retrieving-Objects

Now you can store Employee object in the ViewState as-

  Storing-Retrieving-Objects

Ant can be retrieve from view state as – 

Storing-Retrieving-Objects

 Note that to be serializable, your classes you must meet these requirements:

  • Your class must have the Serializable attribute.
  • Any classes it derives from must have the Serializable attribute.
  • All the member variables of the class must use serializable data types. Any non serializable data type must be decorated with the NonSerialized attribute (which means it is simply ignored during the serialization process).

When to use ViewState

In the following cases can be used –

  • If data is not in extremely large amount of information.
  • If the data is not going to be share across the multiple pages.
  • If the data is not mission-critical.
  • If you don’t want to take up any memory on the server.
  • If you don’t want to impose any arbitrary Usage limits (such as a time-out).

When to not use ViewState

In the following cases it should be avoided –

  • The control never changes. E.g. a button with static text doesn’t need view state.
  • The control is repopulated in every post back. E.g. if you have a label that shows the current date and time, and you set the current time in the Page.Load event handler, it doesn’t require view state.
  • The control is an input control, and it changes only because of user actions. After each post back, ASP.NET will populate your input controls using the submitted form values. This means the text in a text box or the selection in a list box won’t be lost, even if you don’t use view state.

Advantages of using ViewState

Below are the advantages of using view state-

  • No server resources are required.
  • Straightforward implementation.
  • Automatic retention of page and control state.
  • Enhanced security features. The values in view state are hashed, compressed, and encoded for Unicode implementations.

Disadvantages of using ViewState

Below are the disadvantages of using view state-

  • If the data stored in the view state is large enough, it affects page performance.
  • The view state is stored in a hidden field on the page has security issues. Although view state stores data in a hashed format, but it can be tampered with.
  • No support for mobile devices.

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-

 tracing

 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.

 tracing

 
Enabling / Disabling ViewState

You 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 -

Enabling-Disabling View State

To turn off/on view state for a control, set the EnableViewState property of the control to false/true -

Enabling-Disabling View State

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.

ViewState Chunking

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:

ViewState chunking

 When you request a page that generates a view state larger than this, several hidden input fields will be created:

ViewState chunking

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:

MAC
  
Otherwise, you can set the enableViewStateMac attribute of the <pages> element in the web.config or machine.config file for the whole as:

 MAC 

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:

Encryption

Otherwise , you can set the same attribute in the web.config configuration file for the whole site:

  Encryption

• 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.


ViewState Compression

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.

Base Page

Where Compress and Decompress are static methods of the class VSCompression

Compression

 Decompression
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
   • Triplets

Note 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:

  1. Call the RegisterRequiresControlState Method: The RegisterRequiresControlState method informs ASP.NET that a control needs to persist control state. It takes one argument of type Control which is the control that is being registered. It is important to note that registration does not persist from request to request. Therefore, this method must be called on every request if a control is to persist control state. It is recommended that the method be called in OnInit.
  2. Override SaveControlState: The SaveControlState method saves control state changes for a control since the last post back. It returns an object representing the control's state.
  3. Override LoadControlState: The LoadControlState method loads saved state into a control. The method takes one argument of type Object which holds the saved state for the control.

Conclusion

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. 

 

 

Comments (8)

  
vivek_iit
Vivek Thakur said:
An excellent article Sameer..keep it up!
4/29/2010
 · 
 
by
  
samir.nigam
Samir NIGAM said:
thanks a lot sir. plz tell me new topic for next month.
4/30/2010
 · 
 
by
  
Shaitender
awesome article... .. very helpful !!
5/3/2010
 · 
 
by
  
Ashish Anand
Ashish Anand said:
Great Job! Sameer ji.
5/3/2010
 · 
 
by
  
samir.nigam
Samir NIGAM said:
thanks shaitender n ashish g.
5/3/2010
 · 
 
by
  
Sandeep Shekhar
Sandeep Shekhar said:
Very Nice article. Great Job Sir.
5/6/2010
 · 
 
by
  
samir.nigam
Samir NIGAM said:
thanks dear.
5/6/2010
 · 
 
by
  
Mark
Mark said:
One note that we've seen when viewstate gets really large and maxPageStateFieldLength is used to chunk it up is that InvalidOperationException ("Operation is not valid due to the current state of the object." can happen.  This is due to the MaxHttpCollectionKeys value being exceeded.  You can increase the maxPageStateFieldLength or MaxHttpCollectionKeys as two options to resolve it.
9/20/2012
 · 
 
by
  • :*
  • :*
  • :
 *

Top articles

Quick Vote

What kind of email newsletter would you prefer to receive from CodeAsp.Net?