Create a ASP.NET Contact Form
Understanding web controls
If you’re coming from the traditional ASP or PHP environment, the way you’re used to developing form fields is vastly different in ASP.NET. Instead of using <input> tags, we use web controls. When Microsoft created ASP.NET, it basically reinvented web controls that run on the server-side, and then sends back an HTML equivalent. For example, a text box control is a web control, when parsed by the server, generates an HTML input tag. When the generated HTML comes back from the server, the ASP.NET engine includes special values for each control, such as the name attribute which comes from the ID of the control. We’ll see more on that shortly. The most common types of web controls include:
- Text boxes
- Radio buttons
- Drop down lists
- Check boxes
In order to create our ordinary input fields, we’ll be using text box web controls. Let’s add three of them to our file by using the code below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="contact.aspx.cs" Inherits="contact" %> <!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></title> </head> <body> <form id="form1" runat="server"> <h3>My Contact Form</h3> <table id="contact" cellspacing="0"> <tr> <td>First Name:</td> <td><asp:TextBox ID="FNameTB" runat="server" /></td> </tr> <tr> <td>Last Name:</td> <td><asp:TextBox ID="LNameTB" runat="server" /></td> </tr> <tr> <td>Email:</td> <td><asp:TextBox ID="EmailTB" runat="server" /></td> </tr> <tr> <td>Comments:</td> <td></td> </tr> </table> </form> </body> </html>
As you can see from the example above, our web control(s) look a bit odd, but really they’re simple. Using the first one as an example, let’s analyze it:
<td><asp:TextBox ID="FNameTB" runat="server" /></td>
We nest the web control inside a table cell. The web control parts are:
- <asp:TextBox
- Instructs the ASP.NET engine to parse this control as in input field in HTML
- ID=FNameTB
- Each web control must have a unique name. This also serves the purpose of accessing the controls properties and methods in our code-behind file
- Runat=server
- Instructs the control to be run at the server
We purposely left the comments field alone for the moment, but we’ll get to it in a moment.
We'll continue with opening our web form in a browser next.