Introduction
In this article, I would explain about View State in ASP.NET, What is it and how it works.
Have you ever wondered why coding in ASP.NET is so much fun, easy, and less coding time compared to Classic ASP or any other languages such as PHP, JSP ?. One of the reason behind this was ViewState. Every Control in ASP.NET comes with ViewState enabled by default and with the power of ViewState, all your control can remember its values after page post back. ViewState can help you minimize your coding downtime however it has its own pros and cons. Read this article, and you can understand how to minimize your page ViewState data and improve your site performance. You can see the values of ViewState easily by viewing the source of aspx page. You should be able to see that there is hidden values called ViewState. Code sample for ViewState can be seen below
<input type="hidden" name="__VIEWSTATE" value="dNrATo45Tm5QzQ7Oz8AblWpxPj3455E9M0Aq765QnCmP2TQ==" />
ViewState is stored as base 64 encoded strings in name - value pairs.
Main
By Default ViewState is enabled on all controls. However you can disabled ViewState for performance issues. If you do not need your controls to remember its values, then it is best practice to disable the ViewState. It will save you heaps of time when rendering the control during postback event.
ViewState can be enabled and disabled in any of the following ways.
- Page Level
- Control Level
- Application Level
- Machine Level
To enable or disable ViewState in the Page Level, use the following in the Page directive of the ASP.NET page.
<%@ Page EnableViewState ="False|True" %>
To enable or disable ViewState in the control level, use the following code
<asp:TextBox id="txtCode" runat="server” EnableViewState="false|true" />
To enable or disable
ViewState in the Application Level, use the following code in your
web.config files.
<pages enableViewState="false|true" />
To enable or disable ViewState in the Machine Level, use the following code in your
machine.config files.
<pages enableViewState="false" ... />
Using ViewState Programmatically
ViewState is infact a hidden field that you can use to store data per page level. Not like Session Variables,where you can store and retrieve data from all the page within the same application.
If you want to store and retrieve data only on particular page, then ViewState might be the best candidate for this. ViewState can be used with the following types of data
- Primitive types
- Arrays of primitive types
- ArrayList and Hashtable
- Any other serializable object
Code sample on how to store and retrieve ViewState
//Storing String into ViewState
string sData = "MyData";
ViewState["Data"] = sData;//Retrieving the string Values from ViewState
string sData = ViewState["Data"].ToString();
Performance Issues with ViewState
The size of the ViewState for every page should be as minimal as possible for better performance in page rendering and postback. As you can see that higher ViewState data that you have on particular page will result on higher bandwidth usage cause it gets downloaded to the client browser everytime there is a request.
Therefore for every page that you code, remember to set the EnableViewState =false for every control that you don't need to remember its values during postback event. You can also disable entire page level viewstate to false if you don't need any of the features.
Please note that only controls nested inside FORM runat=server can have ViewState features by default. Further, even if ViewState for a page is disabled, still the page itself saves about 20 bytes of information into ViewState to distribute post back data and ViewState values to the correct controls on post back. So, for pages that do not post back at all, remove the runat="server" tag completely for a reduction of the page size by an amount of 20 bytes
For controls such as DataGrid,Repeater,DataList, please remember to switch the ViewState=false if you don't really use it. This is because the ViewState data for that particular control is huge and you can save lots of performance time if you disable it.
There is a code snippet below you can use to check the ViewState of everypage.
object viewStateObject = HttpContext.Current.Request["__VIEWSTATE"];
Response.write(viewStateObject.Length.ToString());
Security Issues with ViewState
ViewState in ASP.NET can easily be tampered cause the ViewState data is not encrypted. Therefore, please do not store important data or information in ViewState. But if you really need to store the important data in Viewstate, few steps can be used to protect and encrypt the ViewState Data.
1. Enable ViewState Mac in page directives or in the web.config level
<%@Page EnableViewStateMAC=true %>
2. Set the machine.config key by using validation such as 3Des or Sha1. Sha1 is more secured compare to 3Des as it produces a larger hash than MD5 and is cryptographically stronger.
You need to edit your machine.config files like this.
<machineKey validation="3Des" validationKey="AutoGenerate,IsolateApps"/> or
<machineKey validation="SHA1" validationKey="AutoGenerate,IsolateApps"/>
If you are running WebFarm on your machine, you cannot use AutoGenerate in your validationKey, hence you must set the same key for all your web farm machine. Otherwise, ViewState generated from one machine could not be POSTed back to a machine farm with different key!. The keys should be 128 characters long(the maximum) and generated totally by random means.
There is a good tools out there that you can use to generate random key.
http://www.pluralsight.com/tools.aspx.
The tools is called (GenerateMachineKey)
Conclusion
ASP.NET ViewState is a great feature for web developers. It maintains a state of a page as it postback. This article has provided an in depth coverage of this State Management Technique of ASP.NET. However, when using ViewState one should be well aware of the performance considerations of its usage.
It is highly preferable to enable tracing for every page to know the size of the ViewState for a page in the development cycle of a project. The ViewState size should be optimized well before the application goes to deployment to avoid slow and longer downloading time for every pages of your application.