ASP.NET Client Side State Management – Hidden Fields
In the previous posts in this series I introduced the client side state
management and one of its techniques – the ViewState.
Today I’m going to drill down into the hidden fields technique.
As mentioned in the previous post, the ViewState stores its state in a hidden field.
What are Hidden Fields?
Hidden fields technique is widely used in ASP.NET programing.
Hidden fields are html input control with hidden type that store hidden data in
the html. An example for a hidden field can look like this:
In the example above, I chose to show the event target hidden
field in order to indicate that even in postback mechanism hidden fields are
being used. The data stored in a hidden field is available when the form is
Hidden Fields Values
Hidden fields store only one value in their value property.
The value is saved as a string and therefore in order to use it for other types
you need to perform casting. Hidden fields’ data is submitted to the server
only in HTTP post operation. You can see the stored data easily by using the
View Source operation of the browser. You can see it by clicking the right
mouse button and then choosing View Source from the menu (if the operation
is available). Be aware not to use hidden fields to store confidential data!
The values has page context and therefore when you leave a page the data
stored in the hidden fields is disposed.
Server Control Hidden Fields
There are two types of server control hidden fields -
Both types has the same primary Value property to hold the value of the
hidden field. You should choose between these types whenever you need
to use a server side hidden field (A note – The difference between
HtmlControls and WebControls isn’t in the context of this post).
When you don’t use server controls you can use the Request.Form
NameValueCollection to get the hidden field value by providing the client
id of the hidden field. For example the code bellow will return the string
value of the __EVENTTARGET hidden field:
Hidden Fields Example
I got some requests for an example of how to use the hidden fields
inside web forms. The example is very easy to understand.
I have an html input with type hidden. In the first request I fill the
to do a post back to the server and in the post back the value of the hidden
field is inserted into a label control. Pay attention that because I use an html
hidden field that isn’t a server control after a second post back it’s value
will be empty. The only reason that the label will still show a message is because
the label’s default value of the EnableViewState is true.
The web page’s code:
The code behind:
To sum up the post, today I drilled down into the hidden fields technique.
This technique is very popular and is used widely in ASP.NET.
In the next post I’ll continue the tour in the client side state management