ViewState In ASP.NET
View state is a client side state management mechanism. View state does not stored data on server side. Once you stored data in view state then you can retrieve that data from anywhere on the same page.
Creating View State
Storing data in view state is very easy. You can store data in view state by assigning a key that will use to retrieve view state stored data. Below codes are showing to storing data in view state.
Reading View State
Below codes are showing that how to retrieving data from view state. While retrieving you have to cast data type.
if (ViewState["UserName"] != null)
string name = ViewState["UserName"].ToString();}
Enable Disable View State
You can disable view state for a specific page or for the complete application.
Below codes are showing to disable view state from Web.Config file that reflected in the complete application.
Below codes are showing to disable view state on a page.
View State Encryption
When you stored data into view state then internally its store into a html hidden field. View state stores data in hidden field as hashed base64 encoded string format. Below is showing how internal view state storing data into hidden field.
Hidden field hashed string can easily decoded. So its security risk that someone can change or modify that data if data is highly sensitive. To overcome these problems use view state EnableViewStateMac or viewStateEncryptionMode property.
Use machine authentication code(MAC) that created a hash of the view state data and added to encoded view state data and stored into the hidden field of page. When page is posted back, the Asp.Net page framework check hash value and data that stored in view state. if the hash is values do not match then, an exception will be raised that indicate that view state data might be temper.
Use EnableViewStateMac in Web.Config
Use EnableViewStateMac on a particular page.
If your data inside view state is highly sensitive information, then you can encrypt those data by using the ViewStateEncryptionMode property of the page directive or in Web.Config. So your information will be secure but due to encryption and decryption the overall performance of page processing will be decrease. Using ViewStateEncryptionMode property, it will increase the size of data which stored inside hidden field.
Below codes are showing, how you can secure view state encryption for whole application from Web.Config.
<pages viewStateEncryptionMode="Always" /></system.web>
You can also secure view state encryption for a particular page.
Disadvantage of View State
1. Performance issues
2. Security concern