Which is best to use ViewState or hiddenfield
Asked Answered
S

4

10

I have a page in which I want to maintain the value of object between post backs. I am thinking of two ways to maintain the value of objects

  1. Store the value in View Sate
  2. Store the value in hidden field

which is best option to use based on performance

Stercoraceous answered 22/10, 2009 at 17:6 Comment(0)
I
10

Viewstate if you don't need to reference it in client side script. A Hidden field if you do.

Also consider that if the data is sensitive, the Viewstate is encrypted by default, whereas the hidden field, by default, stores it as plain text visible to anyone who knows how to view source.

Edit

Per @Andrew Hare's note on his own answer, I'm editing this. It's an important enough distinction to note. I'd hate for someone to think they were "safe" using the Viewstate based on my oversight.

The Viewstate is NOT encrypted by default, it's stored as Base-64 encoding. It can be decoded fairly easily, so using the Viewstate because it's encrypted by default is not valid. It's better than plain text, but not to anyone with the ability to google "decrypt Viewstate" or "decode Viewstate".

So don't rely on the Viewstate to protect your hidden information in client side code.

An article here tells how to encrypt it properly. (but also warns about performance issues).

Indigested answered 22/10, 2009 at 17:10 Comment(0)
P
3

It doesn't really matter since ViewState is itself stored in a hidden input. Use whichever one is easier for you. If it were up to me I would choose ViewState since the ASP.NET runtime will handle the serialization and deserialization of your objects for you.

Pinniped answered 22/10, 2009 at 17:10 Comment(3)
I'm not sure I agree... Viewstate is encrypted where a hidden field, by default, is not Unless I'm missing something. I normally trust your answers, so I bet I'm missing something.Indigested
No, you make a good point - ViewState can be encrypted (but it isn't always - by default it is simply base-64 encoded). Nice catch! :)Pinniped
Thank you! You're right about the base-64, of course. That's an important distinction. I'm editing my answer to reflect this.Indigested
K
0

I like ViewState - it is much harder to hack - a nasty person could easily submit your page to you with bad data in your hidden fields

Knell answered 22/10, 2009 at 17:8 Comment(0)
D
0

You want to store it in the View State. Hidden fields can be updated on the browser, as they are meant to store information that can be manipulated on the client side. The view state will be validated by asp.net against tampering, where you will have to do that with the hidden field yourself.

Depressor answered 22/10, 2009 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.