WorldofASP.NET : ASP.NET Directory, Tutorial, Hosting, and Source Code
You are 1 of 285 users


WorldofASP.NET >> ASP.NET >> State Management

View State in ASP.NET and understand how it works

This article will explain more details about View State in ASP.NET and the magic behind it
Published Date : 26 Aug 2007
Author : James Douglas
Language : C#
Platform : .NET
Technology : Visual Studio,ASP.NET
Views : 13820
Rating : (2 votes so far)



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.




Other Related and Popular Articles :

Understanding Session Object in ASP.NET 2.0
Understand the different type of session objects available in ASP.net 2.0 and how to use it

Encrypting your ViewState in ASP.NET 2.0
This article explains how to encrypt your ViewState easily in ASP.NET 2.0


Author Profile : James Douglas

I work in a Software House Company in Malaysia (Kuala Lumpur) and I am MCP Certified in C# and Web Application course.
I originally started my programming in Java but later on changed to Microsoft platform because of the simplicity and ease of use.
I love .NET programming and am doing it almost every day now.

Click here to view Author Profile


How would you rate the quality of this content?
Poor Excellent

Comments

#Doubts on View State
24 Nov 2009 8:18 by : ravindra shori

Hello,

I need a clarification on this. Since i feel that what's the use of disabling view state at the page level.

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

#Thanks for this beautiful article on viewstate!
05 Mar 2009 3:31 by : Philip

Nice article. Simple , concise and highly informative.

Thanks a lot, i didnt even know that we could store variable in a page's view state. I thought only asp.net could access viewstate to get the postback control states,

I was asked this recently in an interview and i said it was not possible! :-P

Leave New Comments


Article Content copyright by James Douglas
Everything else Copyright © by WorldofASP.NET 2012

Category
ASP.NET
General .NET
C# Programming
VB.NET Programming
Classic ASP
.NET 3.5
AJAX and ATLAS
Enterprise Systems
Announcements
Earn Cash by writing an article or review
For more info Click here






Legend : - Within 3 Days - Within 6 Days - Within 9 Days

Home | Add Resources | Sponsored Listings | Advertise with Us | SiteMap 1 | SiteMap 2 | Link To Us | Contact Us
© 2002-2012 Worldofasp.net ASP.NET Directory, Hosting and Tutorials | All rights reserved
Our Partners : ASP.NET Web Hosting | ASP.NET Hosting | Australia ASP.NET Hosting | Phone Card | Calling Card