TechRepublic’s free .NET newsletter, delivered each Wednesday, contains useful tips and coding examples on topics such as Web services, ASP.NET, ADO.NET, and Visual Studio .NET. Automatically sign up today!

Accessing form data entered by a user is common task for
ASP.NET developers. There is more than one approach for accessing this data.
Unfortunately, developers often choose a cutting-edge solution even when a
basic approach is just as appropriate.

One good example is utilizing the HttpRequest
class when working with ASP.NET form data. Many developers often bypass this
simple solution in favor of newer features like ViewState
and Session objects or even utilize cookies.

Response class

The ASP.NET HttpRequest class
provides access to various aspects of user submitted data via the Page class’
Request property. The HttpRequest class is a
replacement for the Request object in class ASP. It provides an avenue for
working with a request from a Web client via its various methods, properties,
and collections. The following list includes a sampling of the methods,
properties, and collections:

  • Browser: A property that returns
    an instance of the HttpBrowserCapabilities class
    describing the capabilities of the Web client.
  • Cookies: A collection that returns
    an instance of the HttpCookieCollection class
    containing all cookies sent as part of the Web client request.
  • Form: Returns a NameValueCollection object containing all form fields
    submitted with the Web request.
  • Path: A string property returning
    the virtual path of the Web request. This includes the application root
    folder’s name, subfolders in the path, and the requested filename.
  • QueryString: A NameValueCollection
    object containing all keys and corresponding values passed as part of the
    Web client’s query string.
  • ServerVariables: A NameValueCollection
    object containing HTTP server variables.
  • Url: A property that returns a Url object containing information about the requester
    URL.
  • UrlReferrer: A property that returns a Url object containing
    information about the URL requested before the current request.
  • UserAgent: A string property containing the
    HTTP’s User-Agent header—it identifies the Web
    client used to make the request.
  • UserHostAddress: A string property returning the IP
    address of the client making the request.

These items provide a wealth of opportunities to work with a
Web client’s request, but let’s focus on accessing data entered by the user.
Most notable is the QueryString property which allows
us to access data sent via the URL. You may be familiar with this technique
since sites like TechRepublic and News.com use the QueryString
to track and pass along various bits of information.

For example, I conducted a search for the term VB.NET on TechRepublic, and the following URL was returned:

http://www.techrepublic.com/5046-22-0.html?SearchThis=vb.net&nodeIds=all&go=GO

All data to the left of the question mark in the URL is the QueryString. A key and value combination is separated by an
equal sign with multiple key/value pairs separated by the ampersand (&). In
the URL, the SearchThis variable is assigned to the
value of vb.net in the QueryString.

With this in mind, we can create our own QueryString
value by appending the necessary values to a URL. Once the address is opened,
you may retrieve values from the QueryStringNameValueCollection object using the QueryString
property of the Request object.

For example, the following form allows the user to enter
pertinent data and submit it by clicking the appropriate button.

<%@ Page language="c#" %>

<%@ Import Namespace="System.Text" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head>
<title>TechRepublic.com - Working with .NET Request object</title>
<script language="C#" runat="server">
private void btnSubmit_Click(object sender, System.EventArgs e) {
StringBuildersb = new StringBuilder();
sb.Append("RequestForm2.aspx?Name=");
sb.Append(Server.UrlEncode(this.txtName.Text));
sb.Append("&Email=");
sb.Append(Server.UrlEncode(this.txtEmail.Text));
Response.Redirect(sb.ToString());
}
private void btnClear_Click(object sender, System.EventArgs e) {
this.txtEmail.Text = "";
this.txtName.Text = "";
}
</script></head>
<body>
<form id="Form1" method="post" runat="server">
Name:
<asp:TextBox id="txtName" Runat="server" /><br>
<br>Email:
<asp:TextBox id="txtEmail" runat="server" /><br>
<br>
<asp:Button id="btnClear" runat="server" Text="Clear"
OnClick="btnClear_Click" />

<asp:Button id="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form></body></html>

Notice that the user is sent to another page with the
Response object’s Redirect method, and the URL used in the redirect contains QueryString name and value pairs (one for the name and
another for email).

Note: Special characters and spaces are converted to the
necessary values (according to HTTP specification) when passed via the QueryString. The conversion may be forced with the UrlEncode method contained in the Server class. When
accessing the data, the UrlDecode method is used to
retrieve the data as intended.

The next code snippet contains the page the user is sent to
when submitted the previous page. It accesses the QueryString
object, decodes the data, and displays the values submitted by the user.

<%@ Page language="c#" %>
<%@ Import Namespace="System.Text" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head>
<title>TechRepublic.com - Working with .NET Request object</title>
<script language="C#" runat="server">
private void Page_Load(object sender, System.EventArgs e) {
StringBuildersb = new StringBuilder();
if (Request.QueryString != null) {
sb.Append("User submitted data: <br /><br />");
if (Request.QueryString["Name"] != null) {
sb.Append("Name: ");
sb.Append(Request.QueryString["Name"].ToString());
sb.Append("<br /><br />");
}
if (Request.QueryString["Email"] != null) {
sb.Append("Email: ");
sb.Append(Request.QueryString["Email"].ToString());
}
lblUserData.Text = sb.ToString();
} }
</script></head>
<body>
<form id="frmShowInput" method="post">
<asp:Label id="lblUserData" Runat="server" />
</form> </body></html>

This example demonstrates how easy it is to utilize the QueryString to pass simple data from one ASP.NET page to
another. Many developers often use this technique to pass hidden data or data
not entered by the user from page to page. This may be used for search terms
(as shown in the TechRepublic.com URL), display options, or anything else
applicable.

The example also shows how easy it is to use the QueryString to pass insensitive
data. I stress the word insensitive due to the open nature of the QueryString. That is, the user can see the contents of the QueryString in their Web browser’s address field; likewise,
anybody nearby can view it as well. For this reason, no sensitive data should
use this method to pass information.

Here’s the VB.NET equivalent of both pages:

<%@ Page language="VB" %>
<%@ Import Namespace="System.Text" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head>
<title>TechRepublic.com - Working with .NET Request object</title>
<script language="vb" runat="server">
Sub btnSubmit_Click(sender As Object, e As System.EventArgs)
Dim sb As StringBuilder
sb = New StringBuilder()
sb.Append("WebForm4.aspx?Name=")
sb.Append(Server.UrlEncode(Me.txtName.Text))
sb.Append("&Email=")
sb.Append(Server.UrlEncode(Me.txtEmail.Text))
Response.Redirect(sb.ToString())
End Sub
Sub btnClear_Click(sender As Object, e As System.EventArgs)
Me.txtName.Text = ""
Me.txtEmail.Text = ""
End Sub
</script></head>
<body> <form id="Form1" method="post" runat="server">
Name:
asp:TextBox id="txtName" Runat="server" /><br><br>
Email:
<asp:TextBox id="txtEmail" runat="server" /><br><br>

<asp:Button id="btnClear" runat="server" Text="Clear"
OnClick="btnClear_Click" />
<asp:Button id="btnSubmit" runat="server" Text="Submit"
OnClick="btnSubmit_Click" />
</form> </body></html>

And the second page:

<%@ Page language="vb" %>
<%@ Import Namespace="System.Text" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html><head>
<title>TechRepublic.com - Working with .NET Request object</title>
<script language="vb" runat="server">
Sub Page_Load
Dim sb As StringBuilder
sb = new StringBuilder()
If Not (Request.QueryString Is Nothing) Then
sb.Append("User submitted data: <br /><br />")
If Not (Request.QueryString("Name") Is Nothing) Then
sb.Append("Name: ")
sb.Append(Request.QueryString("Name").ToString())
sb.Append("<br /><br />")
End If
If Not (Request.QueryString("Email") Is Nothing) Then
sb.Append("Email: ")
sb.Append(Request.QueryString("Email").ToString())
End If
lblUserData.Text = sb.ToString()
End If
End Sub
</script></head>
<body> <form id="frmShowInput" method="post">
<asp:Label id="lblUserData" Runat="server" />
</form></body></html>

An inherent feature

If you utilize ASP.NET’sViewState feature in an application, you should notice its
usage of the QueryString variable. By default,
ASP.NET stores an identifier for ViewState in the QueryString object, but you may override this with another
method (custom code). One problem that can arise with ViewState
using the QueryString is the amount of data passed
from page to page. For this reason, it is not always acceptable.

A simple yet subtle feature

I have been working with the QueryString
since I began developing Web solutions many years ago. For many situations,
this simple solution still works, yet many young developers are unaware of it
and lean heavily on newer features like Session or ViewState
objects. Adding the QueryString to your toolbox adds
to your versatility as a developer.