Pierre Greborio.NET

Talking about .NET world

ViewState or not ?

One of the most interesting new feature of ASP.NET (vs ASP) is the new state management mechanism called ViewState. In few words, the page controls retains their state (if enabled) across post-backs in a hidden field (of the page) called __VIEWSTATE. As this is a content of the page, the state is sent between the server and the client for each request, for this reason it shouldn't be used for large amount of data.

I think we should avoid on using ViewState for another reason too. Considering a simple DropDownList control containing no more than 52 items (ie. US States) and a complex form (data gathering) where you have 10 DropDownList all containing the same content. Then, the ViewState will retain 10 lists with exactly the same content ! Not so good.

I think that this is a case where the old-style technique (ASP) works better...loading the index selected in the POST data.

Posted: Aug 15 2003, 10:13 PM by PierreG | with 7 comment(s)
Filed under:

Comments

Andy Smith said:

At the point of having 10 DDL's with the same data in them, one has to wonder why you aren't subclassing DropDownList to have a StatesDropDownList, which you can populate with data before viewstate is turned on.
# August 15, 2003 5:01 PM

Addy Santo said:

You don't have to make such inclusive decisions - you can and should fine-tune your viewstate usage on a per-control level. If you don't want 10 ddls persisting to viewstate- turn them off. Got something else which you DO want to save- keep it on.

It is all a matter of tradeoffs- state vs programming effort, performance vs. bandwith, etc.
# August 15, 2003 5:05 PM

Jason Priestas said:

Much like Addy mentioned.. Set your ViewState at the control-level. Enable only the ones that need to have ViewState. In addition, you could check into caching some of your DDLs.

Hope this helps.
# August 15, 2003 5:27 PM

Wallym said:

The problem is that you will then have to go and reload any dropdowns. Database operations are also expensive, so getting rid of the database roundtrips is a plus to the ASP.NET way. There's lots of ways around this problem.
# August 15, 2003 6:52 PM

Pierre Greborio said:

Well, my post isn't complete at all. All of you noticed it :-)
I don't want says ViewState is a bad solution in a general way, but just in some circumstances (as explained here).

There is a little overhead, where the data must be binded at every request (LoadViewState does the same think ?) but nothing else, if you keep your data into the cache.
# August 16, 2003 4:15 PM

TrackBack said:

# August 26, 2003 6:25 AM

Venkatesulu said:

View state is good when data is small and when you want to have the paging and sorting functionalities in your asp page. It works wonderfully.
# March 24, 2004 10:21 PM