Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewState or HiddenField

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?

like image 758
Richard Ev Avatar asked Jan 08 '09 13:01

Richard Ev


2 Answers

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.

like image 63
d4nt Avatar answered Oct 18 '22 04:10

d4nt


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.

like image 41
Mike Hofer Avatar answered Oct 18 '22 05:10

Mike Hofer