GeekInterview.com
  I am new, Sign me up!
 
GeekInterview.com  >  Interview Questions  >  Microsoft  >  ASP.NET
Go To First  |  Previous Question  |  Next Question 
 ASP.NET  |  Question 77 of 164    Print  
What is view state and how it is maintained?
ViewState in ASP.NET
Introduction
Microsoft ASP.NET Web Forms pages are capable of maintaining their own state across multiple client round trips. When a property is set for a control, the ASP.NET saves the property value as part of the control's state. To the application, this makes it appear that the page's lifetime spans multiple client requests. This page-level state is known as the view state of the page. In Web Forms pages, their view state is sent by the server as a hidden variable in a form, as part of every response to the client, and is returned to the server by the client as part of a postback. In this article we will see how View State is implemented in ASP.NET for state management and we will also see how effectively you can use this object in your web form.

Problems with ViewState
Viewstate has lots of advantages and as well as disadvantages, so you need to weigh carefully before making the decision to use it. As I told you early, view state doesnt require any server resources for its operation. It is passed to the client during every postback as an hidden element. Since it is added with every page, it adds few Kbytes to the page. This effects the loading of the page in the client. Other main problem with Viewstate is, since it is passed as plain text to the client. Anybody can tamper this value, because of this you shouldnt store any important data in the viewstate. View state is one of the most important features of ASP.NET, not so much because of its technical relevance, but more because it makes the magic of the Web Forms model possible. However, if used carelessly, view state can easily become a burden. Although ViewState is freely accessible in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.

Implementation of ViewState
StateBag implements the view state and manages the information that ASP.NET pages and embedded controls persist across successive posts of the same page instance. The class works like a dictionary object and implements the IStateManager interface. The Page and the Control base classes expose the view state through the ViewState property. So you can add or remove items from StateBag as you would with any dictionary object:

ViewState("FontSize") = value

You should start writing to the view state only after the Init event is fired for a page request. You can read from the view state during any stage of the page lifecycle, but not after the page enters rendering mode—that is, after the PreRender event is fired.
The contents of the StateBag collection are first serialized to a string, then Base64 encoded, and finally assigned to a hidden field in the page that is served to the client. The view state for the page is a cumulative property that results from the contents of the ViewState property of the page plus the view state of all the controls hosted in the page.


Decision on ViewState Usage
As We 've discussed here, the view state represents the state of the page and its controls just before the page is rendered in HTML. When the page posts back, the view state is recovered from the hidden field, deserialized, and used to initialize the server controls in the page and the page itself. However, this is only half the story.

After loading the view state, the page reads client-side information through the Request object and uses those values to override most of the settings for the server controls. In general, the two operations are neatly separated and take place independently. In particular, though, the second operation—reading from Request.Form—in many situations ends up just overriding the settings read out of the view state. In this particular case the view state is only an extra overhead. For example consider the following case, we have one textbox in the page and a link button. If you are typing the some values in to the textbox and the posting the page using linkbutton. After postback, value in the textbox is retained though you enable or disable the viewstate. In this case you shouldnt enable viewstate for this textbox. Viewstate value is overridden by request.form values, since loadpostdata fires after loadviewstate view event in the Page lifecycle.

But if you consider that readonly property of textbox is set to False by default. Then in the Page_Load if you are trying to change its readonly property to true based on certain condition. So after setting readonly property in Page_Load and if it is posted back by clicking linkbutton. To retain its readonly property across postback, we need to enable viewstate for this property. Otherwise this property wont be retained across postback.

Viewstate in DataGrid
If you have Set EnableViewState to true for a DataGrid which is having thousands of record. Then you will end up having viewstate size more than 10 KBytes. But if you disable viewstate, you will not be able to fire any events in DataGrid. Postback and acting on postback relies on Viewstate. So if it is readonly datagrid and if you are not going to use paging and sorting provided by datagrid, then you can disable viewstate. But if you want use above mentioned feature of DataGrid, then you can not disable ViewState in DataGrid. So to avoid excessive load on client machine because of viewstate . You can disable viewstate for each item in DataGrid. Disabling can be done in two ways, one way is disabling each itemtemplate columns viewstate to false.








Other way is by disabling viewstate for each datagrid item in Pre-Render event handler.

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles
MyBase.PreRender
Dim dgi As DataGridItem
For Each dgi In DataGrid1.Items
dgi.EnableViewState = False
Next
End Sub

Conclusion
The view state is a key element of an ASP.NET page because it is the primary means to persist the state of the Web server controls. Whenever the page posts back, the state is restored, updated using the current form parameters, then used to run the postback event handler. Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE. In this way, the view state is not cached on the client, but simply transported back and forth with potential issues both for security and performance. Since it is performance overhead, you need to decide properly when and where you should use viewstate in your webform.




  
Total Answers and Comments: 2 Last Update: July 02, 2009     Asked by: Shiv 
  
 Sponsored Links

 
 Best Rated Answer

No best answer available. Please pick the good answer available or submit your answer.
October 18, 2006 14:46:24   #1  
cynthia justin        

RE: What is view state and how it is maintained?
view state allows the state of objects to be stored in a hidden field on the page.it is transported to the client and back to the server and is not stored on the server or any other external source.view state is used to retain the state of serverside objects between post backs.
 
Is this answer useful? Yes | No
July 02, 2009 01:00:13   #2  
ketan.Bhatt Member Since: July 2009   Contribution: 1    

RE: What is view state and how it is maintained?
Session variables are maintained for particular session like for particular user only so any user related information has to be saved in session variable. While application variables are maintained for whole application. Whole application related information is to be stored in application variables.
 
Is this answer useful? Yes | No

 Related Questions

1)How will you load dynamic assembly? How will create Assemblies at run time? 2)How to maintain View State of dynamically created user controls? For example, If I am creating few instances ?
Read Answers (1) | Asked by : prangyasri jena

Latest Answer : View state is of maintaining the state of the object until the page is destroyed. In the sense viewstate maintains the state of the object in all the postbacks. Dataset can be stored in viewstate. ...
Read Answers (5) | Asked by : Deepu94

ViewState in ASP.NET IntroductionMicrosoft ASP.NET Web Forms pages are capable of maintaining their own state across multiple client round trips. When a property is set for a control, the ASP.NET saves 
Latest Answer : Session variables are maintained for particular session like for particular user only, so any user related information has to be saved in session variable.  While application variables are maintained for whole application. Whole application related ...
Read Answers (2) | Asked by : Shiv

Latest Answer : try{Connection.Open()}catch{...}finally{ Connection.Close()}The finally block will ALWAYS execute regardless of exception. ...

Latest Answer : Application state is global to the application regardless of the number of application instances. All instances share the same application state variables. Each instance has its own session variables. They are stored at the server end. One use of session ...
Read Answers (6) | Asked by : lakshminarayanan

Latest Answer : There are 3 types of style sheets1. Inline2. Embeded3. External ...
Read Answers (3) | Asked by : Anita Singh

Latest Answer : By default HTTP is a stale less protocol. It means it considers each request as a new request. Solution for this problem is state management. State Management is a technique used to maintain the state of between HTTP Request and Response. There ...

Latest Answer : Cookie Information will be stored in a txt file on client system under a folder named Cookies. Search for it in your system you will find it. Coming to Session State As we know for every process some default space will be allocated by OS. In case ...
Read Answers (2) | Asked by : S S REDDY

Latest Answer : View State data is stored in Hidden Field. This is fine as far as small amount of data is stored. What will happen if I want to store large chunk of data (I know View state is not preferred in such scenario, just let us assume). In that case multiple ...

Latest Answer : Application Object and Cached Object both falls under Server side State Management.Application object resides in InProc i.e. on the same server where we hosted our application.Cache Object resides on server side/ DownStream/Client Side.Application Object ...
Read Answers (3) | Asked by : manjunath


 Sponsored Links

 
Related Articles

What is a view

A view is nothing but a window of an existing table by which one can view and can also change the values in tables. The main point aspect of view is views have no storage space. For this reason views are also called as virtual tables. Thus in other words a view is a database object that gives a logi
 

The Interview Snafu

How to turn someone else’s mistake to your advantage Your dream job is about to become reality. A recruiter gave you the heads up about the perfect position at Humungous Conglomerate, Inc. You went through five interviews as well as a battery of psychological tests mandated by their HR de
 

Winning a Job Interview with a Winning Resume

Does your resume unlock your potential, take your skills to the highest level and win you the interview and the job you want now? The job market today is highly competitive and even if you think you have what it takes to get an interview you won’t get over the line without a polished, prof
 

NLP State Management

NLP State Management Introduction A combination of the internal representations of the mind and the physiology of the body form a complete Neuro linguistic state of consciousness Such states are a part of our day to day life Some states bring us empowerment whereas others limit our potential We need
 

UML Elements : State Diagram

UML Elements State Diagram The state diagram is used as a symbol for finite state machines It may also be used to represent state transition tables Of the 13 diagrams available in UML 2 0 the state diagram has some of the most variations In addition to coming in different forms it may also use vario
 

Importance of Proper English during Job Interview

Importance of Proper English during Job Interview Your job interview is crucially important and it will determine whether or not you will get the job Depending on the type of job you re going for it is very important for you to use proper English In most cases jobs which offer higher salaries will h
 

The Current State of Enterprise Resource Planning

The Current State of Enterprise Resource Planning To analyze the future trends of Enterprise Resource Planning it is first important to look at the current state of this industry While this tool was originally used for manufacturing and human resources it is now being used in areas such as customer
 

HR Interview - HR Interview Mistakes You Will Want To Avoid

HR Interview Mistakes You Will Want To Avoid The job interview can be a stressful process This is especially true for those who are going after a competitive position Your nonverbal communication combined with the answers you give during the interview will determine if you are hired mosgoogle While
 

HR Interview - Behavioral HR Interviews

Behavioral HR Interviews As the name implies a behavioral interview is an interview that is held by a human resources department to determine if an applicant has the behaviors that are appropriate for a job The company must know how an applicant will behave in a certain situations mosgoogle The logi
 

HR Interview - How To Prepare For Your HR Interview

How To Prepare For Your HR Interview Before you begin thinking about how you are going to dress for the interview it is important to do your research first You should learn everything you can about the company you wish to work for When you have detailed information about your employer you will conve
 

About Us -  Privacy Policy -  Terms and Conditions -  Contact -  Ask Question -  Propose Category -  Site Updates 

Copyright © 2005 - 2009 GeekInterview.com. All Rights Reserved

Page copy protected against web site content infringement by Copyscape