Using ASP.NET Request Objects
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 quantitiessuch 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 tagsthey 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 <. 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.