简体   繁体   中英

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?

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.

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 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).

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM