views:

1025

answers:

3

If I have a simple piece of data to store (an integer or string for example) I might choose to store that in ViewState, or using a HiddenField control.

Why would I choose one over the other?

ViewState

  • Hard for the user to decode (thought not impossible), which might be desirable

HiddenField

  • Value can be used in JavaScript

Are there other pros and cons?

+4  A: 

Not really, ViewState is actually stored in a hidden field so the only real difference is the encoding.

Unless you need to manipulate the value with JavaScript or you hope to turn off ViewState on this page altogether then I'd use ViewState. Mostly just because there are third party tools (like this one) which understand ViewState and which won't understand your custom hidden field.

d4nt
A: 

The ViewState is stored in the page itself so it increases the page size and it may cause performance issues.

Also we can configure the application to save the viewstate on server rather than on page itself which might protect from some security issues.

Jomit

Jomit
I'm not sure that the page size argument is valid here - page size will increase regardless of whether I store my value in ViewState or add an additional control to the page and store the value there
Richard Ev
Agree with Richard E regarding the page size argument; on the other hand, agree with Jomit about being able to store viewstate on the server.
Mike Hofer
+1  A: 

From a maintainability point of view, I'd use ViewState. It's less code for you to write, which comes down to fewer points of failure in your software. It also means that any developers coming after you will have an easier time maintaining your solution.

If you're not entirely comfortable with that, write a property accessor on the page that acts as a facade to retrieve the value from the ViewState. Later, if you feel compelled to convert it to a hidden field, the accessor can handle that switch seemlessly for the rest of the code. Just be sure you document your reasons for doing so.

Mike Hofer