Later Today: ASP.NET Tutorial 2: Introduction to C#

ASP.NET Tutorial 7: Intro to .NET Forms

Your web browser functions by sending requests to a web server, and then interpreting the web server’s response. Headers are the data that your browser sends to the server, or receives from the server as part of this “invisible” request-receive communication process.

There are two types of headers: Request and Response.

Request Headers are those that your browser sends to a server, usually to tell the server that you want it to give you a specific webpage or file (ie: Request information). When you send form data to a server using the POST method, that data is sent along with the headers (using each form element’s “NAME” attribute). Alternatively, when you send a form using the GET method, the data is passed along in the query string (URL) instead.

Response Headers are the headers that the server sends back to your browser, usually followed by whatever data your browser requested.

You can use Request["fieldname"] or Request.Form["fieldname"] to get POST data as easily as you can use Request.QueryString("fieldname") to fetch GET data. This is particularly handy if an ASPX page needs to process data sent to it from a different page.
When sending data to a webpage using the GET method, the form data is passed along as part of the URL. Data passed this way is referred to as a “querystring”. Data passed along as a querystring is encoded (because in order to be a valid URL certain characters need to be replaced) and sent as key-value pairs. The “key” is the name of the field, and “value” is whatever data was contained in that field. A URL with GET data in it looks something like this:

www.example.com/?key1=value1&key2=value2&key3=value3

The querystring starts with a question mark ( ? ) and each following key-value pair starts with an ampersand ( & ). Part of the encoding process replaces these characters with placeholders so that the URL remains valid and the querystring does not break. Encoding (and decoding, when you are working with data sent this way) is handled automatically by .NET.

Prerequisites: A basic understanding of HTML form elements.

This article introduces the use of forms in an ASP.NET webpage. Before you begin, you should already have a basic understanding of HTML form elements. If you need a refresher, we will briefly discuss the use of classic form elements on an ASPX page, but the focus of this article will be on the use special ASP.NET form elements.

> Intro to HTML Forms

This section briefly discusses how classic HTML-only forms function.

Classic HTML forms consist of these three things: a form element, a number of input elements (for collecting data), and a submit button (which triggers the form to send).

The form element contains all the other elements and (when the submit button is clicked) tells the browser where to send all the data (called the “action”) and how to send it (called the “method”). Here’s a basic HTML form:

(HTML) A Basic Form:
<input type="text" name="tbTextbox1" id="tbTextbox1"/>

And on a webpage, the above HTML looks like this when it’s rendered by the browser:

Simple Form Example 01

With these classic html forms, when you click the submit button your browser gets the data from the form and sends it to the URL listed in that form element’s action attribute. Notice how the form element also has a method attribute? This tells the browser whether it should send the form using request headers (post) or as part of the URL (get). The web server then uses that data in some way (using a server-side technology like ASP.NET or PHP) and generates a webpage in response (usually based on whatever information it was sent).

> Intro to ASP.NET Forms

This section introduces ASP.NET’s way of handling forms.

While you could use classic form elements in your ASP.NET webpages (those are pages that end in .aspx), .NET comes with a handful of tools that can make creating and working with forms much quicker and more powerful than ever before.

Every webpage in .NET contains a single form element by default, so you can easily start adding form elements to any page. This form element can be found either in your individual aspx files (in .NET 3.5/VS2008) or your Site.master file (in .NET4/VS2010).

Note: In .NET, a webpage can only contain a single server-handled form element. If you MUST have multiple forms, you will need to build them the old fashioned way and have an ASPX page catch and process the data separately.

ASP.NET & Classic Forms Compared

A handy list of available .NET form elements is located under the Toolbox panel of your copy of Visual Studio/Visual Web Developer (usually found along the left side of the window). You can either drag-n-drop items from the Toolbox anywhere on the page, or simply double-click an item in the toolbox to insert it wherever your cursor was located in the editor window. Alternatively, you can simply type in the asp elements you need (once you start to have them memorized).

Below you will find comparisons between some classic HTML form elements and their ASP.NET counterparts:

Form (HTML):
<form method="get" action="" id="frmForm"></form>

Form (ASP.NET):
<form runat="server" method="get" action="" id="frmForm"></form>



TextBox (HTML):
<input type="text" id="TextBox1" name="TextBox1"/>

TextBox (ASP.NET):
<asp:TextBox ID="TextBox1" runat="server">



Hidden Field (HTML):
<input type="hidden" id="HiddenField1" name="HiddenField1">

Hidden Field (ASP.NET):
<asp:HiddenField ID="HiddenField1" runat="server" />



DropDown/Select List (HTML):
<select id="DropDownList1" name="DropDownList1">
    <option value="1">Selection #1</option>
    <option value="2">Selection #2</option>
</select>

DropDown/Select List (ASP.NET):
<asp:DropDownList ID="DropDownList1" runat="server">
     <asp:ListItem Value="1">Selection #1</asp:ListItem>
     <asp:ListItem Value="2">Selection #2</asp:ListItem>
</asp:DropDownList>



DropDown/Select List (HTML):
    <input type="radio" name="gender" value="1" /> Selection #1
    <input type="radio" name="gender" value="2" /> Selection #2

DropDown/Select List (ASP.NET):
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
     <asp:ListItem Value="1">Selection #1</asp:ListItem>
     <asp:ListItem Value="2">Selection #2</asp:ListItem>
</asp:RadioButtonList>



Button (HTML):
    <button type="btnSubmit" name="submit">Submit</button>

Button (ASP.NET):
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" />

It’s important to note that all of these asp elements will actually render out to classic HTML. The reason these are different from standard HTML at all is so that the server (and the Visual Studio software) can be fully aware of them (since it is going to be sending the data to itself). This allows you to perform all sorts of neat actions on these elements from the code-behind class – so you can build programming that affects your form (such as changing CSS/styling of an element if it’s incorrect).

Unlike classic HTML, you also don’t need to specify any “name” attribute. You simply specify the “id” and .NET will handle the rest for you.

Finally, form elements in .NET must contain a “runat” attribute – this tells the server that this needs to be rendered out by the server before the finished HTML is sent to the user’s web browser. If this attribute is missing, it will assume that the element is plain X/HTML and it be sent to the browser as-is (which wouldn’t be much good to anyone since elements beginning with <asp: are not valid HTML).

Note: By default, the form element in .NET only has one attribute, runat="server" in it. Unless you specifically specify otherwise, the form will automatically assume that you want to use action=”" and method=”get” . For example, if you had a form at www.example.com/contact then that form would send the data back to itself at www.example.com/contact (leaving the action attribute blank will always cause a form to send data to its own page). This is generally what you want in .NET with few exceptions, but it’s important to be aware of these defaults.

> Reading the Data

This section explains how the server reads the form data
Forms can send data to a server in one of two ways – using the GET method to send it as part of the URL or using the POST method to send it as a request header. Both methods have advantages and disadvantages…

GET vs POST

• The GET method is not a secure way to send data and can make for a very large querystring (see Amazon.com for an example), but also perma-linking possible. This is especially useful when you want your users to be able to bookmark or link page to a page after they’ve completed a form. It also allows you to send an email with a link to a dynamically generated results page. Most database-driven Content Management Systems (Wordpress, Drupal, etc) use this method for determining which webpages to display. Although beyond the scope of this series, URL rewriting can be used to make querystrings look more friendly and easy to remember (Hence, www.example.com?node=2346234723 can instead be made to look like www.example.com/archive/todayspost/).

• The POST method is more secure than GET since it passes the data to the webpage in the request headers, which are invisible to users without special tools. Using POST is especially handy when you don’t want users to be able to link back to or bookmark a results page.

Regardless of which method you choose and under what circumstances, getting the information using .NET is simple.

Requesting Data in .NET

We’ll cover this in more detail in the next tutorial, but getting a variable in .NET is actually simple. By default, a .NET form will send the form data to itself (this is called, not unusually, a postback) using the GET method (unless you’ve specified something different in your form element).

One really cool thing about .NET is that you can work with form elements in your code-behind class (aspx.cs file) simply by calling them by name. Let’s assume you have the following form code on your webpage (aspx.cs file):

ASPX Web Form:
<form id="form1" runat="server">
  <p>
    <label for="TextBox1">Email:</label>
    <asp:TextBox ID="tbEmail" runat="server">
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click"/>
    <asp:Literal ID="litMessage" runat="server"></asp:Literal>
  </p>
</form>

And the following is your code-behind class (there’s no code to handle the form submission yet)…

ASPX Code-Behind Class:
public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    //Stuff to do when the page first loads
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    //Stuff to do when the button is clicked (Page_Load() still happens first)
  }
}

Tip: You can have Visual Studio automatically create the button’s method for you. To take advantage of this feature, simply add a button to your webpage, switch to Design View, and then double-click on the button. Wah-lah! There is now a method for the button in your code-behind class and everything is named and linked up for you automatically.

Now if all you wanted to do was display the text entered into tbEmail on the page, you could add it to the asp:literal element we included called litMessage.

ASPX Code-Behind Class:
public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    //Stuff to do when the page first loads
  }
  protected void Button1_Click(object sender, EventArgs e)
  {
    //Set litMessage's Text property to the same as tbEmail's Text property
    litMessage.Text = tbEmail.Text;
  }
}

It’s as simple as that. Because .NET remembers the name of your runat=”server” elements, you can simply access the elements by name. Keep in mind, however, that tbEmail only refers to the element itself – to get the text the user entered, you need to specify that you want the Text property. Also, you could just as easily assign tbEmail.Text to a string variable to manipulate however you see fit.

Note: If you have your .NET form posting to a page other than itself (even another aspx page in the same project), you will not be able to call the form elements by name. Instead you will need to use the Request() class to get the data.

That’s it for ASPX form basics. If you need to brush up on your classic HTML forms, I recommend checking out W3Schools.com. There’s really not a lot of difference between building forms in classic HTML and building them in .NET (other than some terminology) – but if you don’t already have a basic understanding of HTML forms, understanding them in .NET is even more difficult.

The next article will deal more closely with what you do with form data once the user has submitted it.

No Comments

Post a Comment

You must be logged in to post a comment.

RSS Twitter LinkedIn Facebook
Doing neato things with JavaScript, please wait...