Reputation: 89
I have a doubt why we use ViewState because Session can keep its state throughout the application. Then why is the need for ViewState which can keep the state only in a single Page?
Upvotes: 2
Views: 1443
Reputation: 73721
If the user opens several instances of the application in different tabs of the browser, the data stored in Session will be shared by all of them (unless something special is done to avoid that). One instance modifying a value in a Session variable will overwrite the same variable saved by the other instances, causing a mixup of the data. Using ViewState ensures that each instance is not affected by the others.
Upvotes: 2
Reputation: 401
First Thing first is to know what is
View State
Is information of a particular page in webforms
. It is stored in hidden field. It is used to maintain that the page remembers what he did on it the last time.
Session Is information that is related to a specific session.i.e. certain browser
now coming to your question
When to use and not use is a cluster F......
as all have their specific pros and cons specially ViewSate
is more a con I guess since the MVC was introduced.
One can use viewstate
to store values to remember when its page have a post back as every time, when a page is in a post back stage it removes all the values of user controls .i.e. like Label
and TextBox
in asp.net . So to keep the value you've toEnableViewState
property to true
Session on the other hand is used when you wish to move from page to page, to keep some specific value for all the pages. For example: one keeps UserId
in session so he can visit all the page which need some kind ofauthorization
or authentication
Update
As you've changed you question while I was type:
In that case
Sessions is for specific time whereas Viewstate
does not as Viewstate
is a temporary storage mechanism. Controls
that use viewstate
have their state
rendered into the html page as hidden input.
Hope this will help you in any way, and don't worry about vote down you'll get use to of it
Upvotes: 3