ViewState or HiddenField

If I have a simple piece of data to store (for example, an integer or a string), I can choose to save it in ViewState or using the HiddenField element.

Why should I choose one by one?

ViewState

  • It is tough for the user to decode (thought not impossible), which may be desirable

hidden

  • Value can be used in javascript

Are there any other pros and cons?

+7
viewstate hidden-field
source share
5 answers

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

If you do not need to manipulate the value using JavaScript or you want to disable ViewState on this page as a whole, I would use ViewState. Mostly just because there are third-party tools ( like this one ) that understand ViewState and that won't understand your own hidden field.

+6
source share

In terms of maintainability, I would use ViewState. This is less code to write, which reduces the number of errors in your software. It also means that any developers who come after you will have an easier time supporting your decision.

If this is not convenient for you, write the accessor property on the page, which acts as a facade for retrieving the value from the ViewState. Later, if you are forced to convert it to a hidden field, the accessor can easily handle this switch for the rest of the code. Just make sure you document your reasons for this.

+3
source share

The ViewState is stored on the page itself, so the page size increases, and this can cause problems .

We can also configure the application to save the viewing state on the server , and not on the page itself, which can protect some security problems.

Jomit

0
source share

Viewstate only works on the page you are on, or send back. Using a hidden field, you can access the data on the next page that you go to (as well as other data) using the PreviousPage method of the Page object, like so:

string term = ((TextBox)Page.PreviousPage.FindControl("txtSearchTerm")).Text; 
0
source share

The hidden field is invisible on the page, and their values ​​can be viewed in the view source, but the view state value is encoded and cannot be read.

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

0
source share

All Articles