Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

The hidden field are invisible on page and their values can be viewed in view source but the value of view-state are encoded and are not readable.

The hidden field value are posted on next page. (Note: use server.transfer to get the value of hidden fields).

Viewstate is only good on the page you are on or posting back to. With a hidden field you can access the data on the next page you navigate to (as well as other data) by using PreviousPage method of the Page object like so:

string term = ((TextBox)Page.PreviousPage.FindControl("txtSearchTerm")).Text;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top