This tutorial will demonstrate how to use the hidden field control to store data with ASP.NET 4.0 and C#.

The hidden field is a control that stores a value but does not display that value to the user. It would be similar to using a label that had a value, but was hidden. The hidden field is rendered as an HTML element. The hidden field can be used to store data that needs to persist across multiple post backs. This control can come in handy when other methods of storing data across post backs are not available, such as session states and cookies.

Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we’ve found so far.

Using the HiddenField

There are two different ways that you might want to use the hidden field, from a javascript function or from the code behind of our page. In this example, we will be demonstrating both ways. To do this, create a new ASP.NET Empty Web Site and:

  1. Right click the project in your solution explorer.
  2. Select add new item…
  3. Select a web form.
  4. Name it ‘Default.aspx’.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a label onto the web form.
  8. Drag and drop a hiddenfield onto the web form.
  9. Set the Value property of the hiddenfield to ‘Hello Hidden Field!’.

To access the hidden field in our code behind, we can simply add the following code to our Page_Load event method that will set our label to the value of the hidden field:

Next, to access the hidden field from a javascript function, we can add in a button to the Default.aspx page as follows:

Then, we can simply add in the following JavaScript function to run on the event that our button is clicked to display the hidden field value:

Testing

To test this out, load up the web site. Notice that your label contains the value of the hidden field. Next, click the button and notice the alert popup that displays to us the value of our hidden field. The hidden field can be used for many different purposes, but is not suitable to hold sensitive information. This is because the user can view the value of the hidden field in the page source via your web browser.
Download Source Files