Home > Articles > Programming > ASP .NET

Using ASP.NET Request Objects

Learn what the ASP.NET Request object has to offer you and how to use it by exploring the Form, QueryStrng, ServerVaribles, and Cookies collections.
This chapter is from the book

This chapter is from the book

In this chapter

  • Forms
  • QueryString
  • ServerVariables
  • Cookies
  • Other Request Objects

The first two chapters looked at Active Server Pages from a high level, discussed distributed application development, and talked about the built-in ASP.NET languages.

In this chapter, you'll see how to use the ASP.NET Request object. This important object runs on the server and you use methods, properties, and collections to program it. You'll learn about the most commonly used Request object and collections, and how to use them in your ASP.NET applications.

As you've already seen, VB, C#, and JScript inside ASP.NET pages enable the server to modify content that is seen in the Web browser. This enables you to collect and display values such as the current date and time and the values of various HTTP variables. You can use this information to make decisions about what to send the client browser, based on known quantities—such as with data that's based on the current date.

Altering HTML content based on things such as date and time is dynamic, but not active. Visitors to a Web site that simply displays dynamic data based on the date, time, or other variables are passive receptors of information. Their only input to the information path they follow is defined by links they click in the Web pages. So now it's time to consider how to use ASP.NET to actually communicate with the user.

Traditionally, Web browsers have communicated with servers through forms, where information was sent to a server CGI program. The program could then examine this information and produce a new HTML document on the fly to be sent back to the requesting client.

Alternatively, in some situations, the page might have contained hyperlinks that included information about the user's selections. This is often seen in Web search pages where clicking on a link in the page sends one or more values back to the browser. The additional information is appended to the URL to form a query string.

In both of these cases, ASP.NET enables you to collect information that you can use in your code.

Forms

The information stored in the Request object collections originates from the client, and is passed to the server as part of the HTTP document request. The server decodes all this information, and makes it available to ASP.NET through the collections, which are part of the Request object's interface.

Apart from the normal information contained in the HTTP header portions of the request, one way that the browser can send specific information to the server is with a form. This can be seen in the referring HTML page with a <FORM> tag.

Using a TextBox in a Form

The following example asks users to enter their name and address. A Submit button sends the information to another page (indicated by the action attribute in the <FORM> tag), and the Reset button clears the form. The following code contains a form with two text fields and Submit and Reset buttons. On the Web site, the code has some formatting tags—they have been removed here for clarity.

<form method="POST" action="TextBoxResult.aspx">
 Name: <input type="text" name="Name" size="20"><br>
 Address: <input type="text" name="Address" size="20"><br>
 <input type="submit" value="Submit" name="B1">
 <input type="reset" value="Reset" name="B2">
</form>

NOTE

This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then TextBox. You can also see the page in Figure 3.1.

Figure 3.1 This form enables users to enter two fields.

Notice that the <FORM> tag has an action attribute that specifies a URL. The browser goes to this URL when the Submit button is clicked. The form information arrives as part of the HTTP header, and is easily accessible by the Request object. To get information from a form field, simply declare a string variable into which the information will be placed, and retrieve the string data with a Request.Form() method call. The following code shows how to obtain the string contained in the Name field of the form:

Dim strName as String
strName = Request.Form( "Name" )

The entire code that gets the name and address string data, and displays it in the outgoing document, can be seen in the code fragment that follows. I'll spend more time in Chapter 4 talking about how to output to the outgoing document. For now, when you see an expression such as

<%=strName%>

you will know that it is taking the contents of the strName variable and sending it out in the HTML document.

<%
 Dim strName as String
 Dim strAddress as String
 strName = Request.Form( "Name" )
 strAddress = Request.Form( "Address" )
%>

The name that was submitted was: <font color="red">
 <%=strName%></font><br>
The address that was submitted was: <font color="red">
 <%=strAddress%></font><br>

NOTE

This code is part of the page that is invoked by filling out the form shown in Figure 3.1 and clicking on the Submit button. You can see the rendered page in Figure 3.2.

Figure 3.2 Here, you can see the data obtained from Request.Form().

Using a <SELECT> Tag in a Form

Many times, rather than offer users an editable text box, you need to give them a list of predetermined selections. A <SELECT> tag indicates the HTML construct that does this. Within the <SELECT> tag are the choices, themselves found within <OPTION> tags. The following code shows how to use <SELECT> tags to offer users choices. The following code differs from what is on the Web site because the formatting tags have been removed here for clarity.

<form method="POST" action="SelectResult.aspx">
 Flavors:
 <select name="Flavors">
 <option value="Chocolate">Chocolate</option>
 <option value="Vanilla">Vanilla</option>
 <option value="Strawberry">Strawberry</option>
 </select><br>
 Containers:
 <select name="Containers">
 <option value="Cone">Cone</option>
 <option value="Cup">Cup</option>
 <option value="WaffleCone">Waffle Cone</option>
 </select>
 <input type="submit" value="Submit" name="B1">
 <input type="reset" value="Reset" name="B2">
</form>

This code has two <SELECT> tags, each with a different name. One is Flavors and the other Containers. The page that receives this form uses these names to retrieve the form contents.

NOTE

This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Select. You can see the page in Figure 3.3.

Figure 3.3 Two Select objects offer users their choices.

Retrieving the data from the named form select items is the same as retrieving data from a TextBox. Just declare a string variable, and get the data using a Request.Form() method call. The following code shows the code that gets the two selections and sends them out in the HTML document:

<%
 Dim strFlavor as String
 Dim strContainer as String
 strFlavor = Request.Form( "Flavors" )
 strContainer = Request.Form( "Containers" )
%>

The flavor that was submitted was: <font color="red">
 <%=strFlavor%></font><br>
The container that was submitted was: <font color="red">
 <%=strContainer%></font><br>

NOTE

This code is part of the page that is invoked by filling out the form shown in Figure 3.3 and clicking on the Submit button. You can see the rendered page in Figure 3.4.

Figure 3.4 The data obtained from Request. Form().

Using a Check Box in a Form

To offer users a choice that's either on or off, a check box is a good tool. An <INPUT TYPE="CHECKBOX"> tag indicates a choice in HTML code. This tag has attributes with which you can specify its name and its value. When they are selected and submitted, they contain the value that's specified in the Value attribute.

For example, the following check box:

<input type="checkbox" name="Cup" value="ON">Cup<br>

if selected, will contain the string data "ON" when retrieved with the Request.Form() method as follows:

Dim strStringData as String
strStringData = Request.Form( "Cup" )
' If selected, strStringData will contain the text "ON"

The following example offers users two categories, each of which contains three choices. Because the choices are offered with check boxes, they can be combined in any way the user chooses. For example, the user can make two choices in the first category of Chocolate and Vanilla, and one choice in the second category of Waffle Cone. Radio buttons, with which it is possible to make only one choice in a category, are discussed later. The following code differs from what is on the Web site because the formatting tags have been removed here for clarity.

<form method="POST" action="CheckBoxResult.aspx">
 Check the flavors that you enjoy:<br>
 <input type="checkbox" name="Chocolate" value="ON">Chocolate<br>
 <input type="checkbox" name="Vanilla" value="ON">Vanilla<br>
 <input type="checkbox" name="Strawberry" value="ON">Strawberry<br>
 Check the containers that you enjoy:<br>
 <input type="checkbox" name="Cone" value="ON">Cone<br>
 <input type="checkbox" name="Cup" value="ON">Cup<br>
 <input type="checkbox" name="WaffleCone" value="ON">Waffle Cone<br>
 <input type="submit" value="Submit" name="B1">
 <input type="reset" value="Reset" name="B2">
</form>

NOTE

This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Check Boxes. You can see the page in Figure 3.5.

Figure 3.5 Two sets of check boxes offer more flexible choices.

The page that receives and acts on the form data is shown next. It examines the contents of each of the named form fields (Chocolate, Vanilla, Strawberry, Cone, Cup, Waffle Cone) to see whether they contain the value of "ON". If they do, then the corresponding check box was selected.

<%
 If Request.Form( "Chocolate" ) = "ON" Then
%>
You like chocolate<br>
<%
 End If

 If Request.Form( "Vanilla" ) = "ON" Then
%>
You like vanilla<br>
<%
 End If

 If Request.Form( "Strawberry" ) = "ON" Then
%>
You like strawberry<br>
<%
 End If
%>
<hr>
<%
 If Request.Form( "Cone" ) = "ON" Then
%>
You like cones<br>
<%
 End If

 If Request.Form( "Cup" ) = "ON" Then
%>
You like cups<br>
<%
 End If

 If Request.Form( "WaffleCone" ) = "ON" Then
%>
You like waffle cones<br>
<%
 End If
%>

NOTE

This code is part of the page that is invoked by filling out the form in the example shown in Figure 3.5 and clicking on the Submit button. You can see the rendered page in Figure 3.6.

Figure 3.6 Here are the results of the user selection.

Using Radio Buttons in a Form

It's often necessary to create forms that contain multiple groups of related information. For example, you can add two radio buttons to the ice cream form to enable users to identify their gender. The radio buttons should have unique values so that you can distinguish them when you use the Request.Form() method to access the data.

Take, for example, the following HTML code:

<input type="Radio" Name="Gender" Value="Female"> Female
<input type="Radio" Name="Gender" Value="Male"> Male

Now use the following code to retrieve the data in the page to which the submitted form goes:

Dim strStringData as String
StrStringData = Request.Form( "Gender" )

The strStringData variable contains "Female" if the Female radio button was selected, and "Male" if the Male radio button was selected. Note that radio buttons are grouped together by the Name attribute. Within the group one and only one selection can be made.

The following HTML code shows two groups of radio buttons, each of which offers three choices:

<form method="POST" action="RadioButtonResult.aspx">
 <p>Flavors:<br>
 <input type="radio" value="Chocolate" checked name="R1">Chocolate<br>
 <input type="radio" value="Vanilla" name="R1">Vanilla<br>
 <input type="radio" value="Strawberry" name="R1">Strawberry</p>
 <p>Containers:<br>
 <input type="radio" value="Cone" checked name="R2">Cone<br>
 <input type="radio" value="Cup" name="R2">Cup<br>
 <input type="radio" value="WaffleCone" name="R2">Waffle Cone<br>
<input type="submit" value="Submit" name="B1">
<input type="reset" value="Reset" name="B2">
</form>

NOTE

This code (which has had the formatting tags removed) is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Radio Buttons. You can see the page in Figure 3.7.

Figure 3.7 Radio buttons offer mutually exclusive sets of choices.

As shown before, the Request.Form() method is used to retrieve the choice for a radio button group. The result is a string value, and contains whatever was specified by the Value attribute of the selected radio button.

The following code takes the form in the example shown in Figure 3.7 and outputs the string data to the HTML document:

<%
 Dim strFlavor as String
 Dim strContainers as String
 strFlavor = Request.Form( "R1" )
 strContainer = Request.Form( "R2" )
%>

The flavor that was submitted was: <font color="red">
 <%=strFlavor%></font><br>
The container that was submitted was: <font color="red">
 <%=strContainer%></font><br>

NOTE

This code is part of the page that is invoked by filling out the form in the example shown in Figure 3.7 and clicking on the Submit button. You can see the rendered page in Figure 3.8.

Figure 3.8 The radio button data is obtained with Request.Form().

Using a TextArea in a Form

A TextArea is an HTML item that enables users to enter multiple lines of text. It's useful for situations such as user comments, or for allowing users to request information. The following code (which has had the formatting tags removed) shows a TextArea in a form:

<form method="POST" action="TextAreaResult.aspx">
 Some Text:<br>
 <TEXTAREA cols=40 rows=15 Name="SomeText"></TEXTAREA><br>
 <input type="submit" value="Submit" name="B1">
 <input type="reset" value="Reset" name="B2">
</form>

NOTE

This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Text Area. You can see the page in Figure 3.9.

Because users can type in just about anything they want, the text string that you retrieve might contain characters that, when output in an HTML document, don't show up as you expect them to.

Figure 3.9 The TextArea item accepts multiple lines of text.

For example, if a user types in the < character, it doesn't appear as such if you output it to the HTML document. That's because this special character is interpreted as the start of a tag, and doesn't appear as a literal < character. The HTML code that renders it correctly to the user is &lt;. It's difficult to replace all these special characters with their correct HTML equivalents if you intend on outputting strings to the HTML document. For this reason, ASP.NET provides a helper method named Server.HTMLEncode() that takes a string and translates it to a string that renders correctly in an HTML document.

The previous example shown in Figure 3.9 submits a TextArea, and the following code outputs it to the HTML document twice: the first time as is, the second time with the help of the Server.HTMLEncode() method. If the user types in a special character, the first output does not cause a correct rendering, whereas the second does.

<%
 Dim strSomeText as String
 strSomeText = Request.Form( "SomeText" )
%>

<p>The text that was submitted was: <font color="red">
 <%=strSomeText%></font></p>
<p>The HTMLEncoded version of the text that was submitted was: 
<font color="red">
 <%=Server.HTMLEncode(strSomeText)%></font><br>

Using the Form Collection

When a form is submitted, it is actually retrieved as a collection. The Request.Form() method, as I've used it so far, has taken a string argument specifying the name of the form field that's being retrieved.

There might be occasions where you have to enumerate all the form fields. The most common use of this is when you're debugging your ASP.NET applications and need to examine all form field names and values.

You can enumerate through the entire form collection very easily. The following code (which has had the formatting tags removed) is from a page that submits five different form fields:

<form method="POST" action="FormCollectionResult.aspx">
 Name:<br>
 <input type="text" name="Name" size="20"><br>
 Name:<br>
 <input type="text" name="Address" size="20"><br>
 City:<br>
 <input type="text" name="City" size="20"><br>
 State:<br>
 <input type="text" name="State" size="20"><br>
 Zip:<br>
 <input type="text" name="Zip" size="20"><br>
</form>

NOTE

This code is part of the page that you can find at http://www.UsingASP.net, selecting Chapter Examples, Chapter 3, then Form Collection. You can see the page in Figure 3.10.

Figure 3.10 This form has five input fields.

Enumerating the form collection is similar to enumerating any other collection in ASP.NET. You can use a For/Next loop and enumerate through each form field, as the following code shows:

<%
 For Each Item in Request.Form
%>
 Form control name <font color="red">'<%=Item%>'</font><br>
 Form control value <font color="blue">'<%=Request.Form(Item)%>'</font><br>
<%
 Next
%>

NOTE

This code is part of the page that is invoked by filling out the form shown in the Figure 3.10 and clicking on the Submit button. You can see the rendered page in Figure 3.11.

Figure 3.11 You can see the results of the form enumeration.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020