HiddenField Control

Hidden fields are a common trick of the HTML web developer’s trade for carrying information within a page when you do not want that information to be visible to the user—that is, the hidden field provides a way to store state information in the page. For example, you might want to keep track of whether a form on the page has been completed, has been saved as a draft, or is being edited for the first time.

Often, an easier and more elegant way to accomplish this task is to use one of the state mechanisms provided by the .NET Framework (see Chapter 6 for a complete discussion of state). However, sometimes this is impossible, perhaps for performance, bandwidth, or security reasons. (Performance and bandwidth are mostly two sides of the same coin.)

In HTML pages, you might use something such as the following code snippet to implement a hidden field:

<input type="hidden" id="FormStatus" value="Draft Saved">

Indeed, ASP.NET uses a hidden field to implement view state. You can see this by examining the source that is rendered to the browser, via the View → Source menu command in Internet Explorer. (Other browsers have analogous commands.) You will see something similar to the following, where the value attribute encodes all the information saved in view state:

<input type="hidden" name="_  _VIEWSTATE"
   value="/wEPDwUJL0CHlBR...YfL+BDX7xhMw=" />

To reap the benefits of server-side processing, you can use an ASP.NET HiddenField control to generate these hidden fields for use both by the browser and on the server.

In addition to accessing the hidden value through the control’s Value property, ASP.NET also defines an event called ValueChanged for the HiddenField control. This fires on postback when the Value property of the control is different from the previous posting. The event does not cause a postback itself, and unlike most nonpostback controls, the HiddenField does not expose an AutoPostBack property to force an instantaneous postback. As with all nonpostback controls (explained in Chapter 3), notification of the event will be cached until the form is posted back by some other control, at which point the event will be raised in server code.

These features are demonstrated in Example 4-8, in a file called HiddenFieldDemo.aspx. The file contains a TextBox (txtSecretValue) for entering a new value for the HiddenField control (hdnSecretValue), an HTML button (used to execute a client-side function without causing a postback to the server), and an ASP.NET Button called btnPost (to force a postback to the server). A Label (lblSecretValue) displays the contents of the hidden field.

Example 4-8. HiddenFieldDemo.aspx

<%@ Page Language="C#" AutoEventWireup="true"
   CodeFile="HiddenFieldDemo.aspx.cs" Inherits="HiddenFieldDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>HiddenField Control Demo</title>
</head>
<body>
   <script type="text/javascript" language="javascript">
      function ChangeHiddenValue()
      {
         alert("Entering ChangeHiddenValue");
         var hdnId = "<%=hdnSecretValue.ClientID%>";
         var hdn = document.getElementById(hdnId);
         var txt = document.getElementById("txtSecretValue");
         hdn.value = txt.value;
         alert("Value changed");
      }
   </script>

   <form id="form1" runat="server">
   <div>
      <asp:HiddenField ID="hdnSecretValue" runat="server"
         onvaluechanged="hdnSecretValue_ValueChanged" />
      Enter secret value:
      <asp:TextBox ID="txtSecretValue" runat="server" />
      <br />
      <br />
      <input id="Button1" type="button" value="button"
         onclick="ChangeHiddenValue()" />
      <asp:Button ID="btnPost" runat="server" Text="Post" />
      <br />
      <br />
      <asp:Label ID="lblSecretValue" runat="server" />
   </div>
   </form>
</body>
</html>

The HTML button calls the ChangeHiddenValue function, highlighted in the code listing. This function has two alert methods that are helpful in debugging; they can be omitted or commented out.

ChangeHiddenValue demonstrates two equivalent ways of getting a reference to a control on the page, both using the JavaScript getElementById method. This method returns a reference to the first object it finds on the page with the specified ID attribute.

In the first technique, a reference is obtained to the HiddenField control via the ClientID property, which returns the actual ID of the <input type="hidden"> element as rendered on the page by ASP.NET:

var hdnId = "<%=hdnSecretValue.ClientID%>";

Enclosing the server-side code in <% %> tags tells ASP.NET to evaluate that code and place the results there in place of the tags and their contents.

In the second technique, the ID attribute of the TextBox control is passed directly to the getElementById method in the script rather than by injecting it:

var txt = document.getElementById("txtSecretValue");

The HiddenField ValueChanged event is handled by a server-side method, hdnSecretValue_ValueChanged, as indicated by the HiddenField’s OnValueChanged attribute in Example 4-8. The event handler from the code-behind file, HiddenFieldDemo.aspx.cs, is shown in Example 4-9.

Example 4-9. HiddenFieldDemo.aspx.cs

using System;
using System.Web.UI.WebControls;

public partial class HiddenFieldDemo : System.Web.UI.Page
{
   protected void hdnSecretValue_ValueChanged
      (object sender, EventArgs e)
   {
      HiddenField hdn = sender as HiddenField;
      lblSecretValue.Text = hdn.Value;
   }
}

The first line in hdnSecretValue_ValueChanged obtains a reference to the control that raised the event, carried in the sender argument. It casts sender as type HiddenField. Then the Value property of the HiddenField object is used to set the Text property of lblSecretValue.

After you enter a secret value and click the Post button, you’ll see a web page much like Figure 4-5. The Post button does not have an event handler because you don’t need it to perform any function other than to cause a postback to the server.

HiddenFieldDemo at work

Figure 4-5. HiddenFieldDemo at work

Get Programming ASP.NET 3.5, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.