ASP.NET Form Processing Basics

Tweet

In my first article, Getting Started with ASP.NET (which you should read first if you haven’t already), I introduced you to the Microsoft .NET platform, walked you through the installation of the .NET Framework, and showed you how to create a very basic ASP.NET Web page.

In this article, we’ll take the next step on your road to ASP.NET expertise. I’ll demonstrate with an example how ASP.NET can be used to process a simple form submission. As before, all examples will be presented both in C# and in VB.NET.

A Personalized Greeting

Here’s the finished example (hellothere-cs.aspx) from the previous article in this series:

<%@ Page Language="C#" %> 
<html>
<head>
<title>My First ASP.NET Page</title>
<script runat="server">
 protected void Page_Load(Object Source, EventArgs E)
 {
   TimeLabel.Text = DateTime.Now.ToString();
 }
</script>
</head>
<body>

<p>Hello there!</p>

<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>

</body>
</html>

As you’ll recall, this simple page displayed the current time according to the server on which it was running:

My First ASP.NET Page

While effective, you must admit that the greeting on this page is a little impersonal. Wouldn’t it be nice if the page greeted each user by name?

Personalised Greeting

Of course, for this to happen we need to prompt each user for his or her name. To do that, we’ll need a form…

ASP.NET Server Controls

Here’s what we’d like our page to look like as it prompts the user for his or her name:

Submission Form

As you can see, this page contains a text field and a submit button. If you were to create this page with standard HTML, the code for the form would look something like this:

<form action="hellothere-cs.aspx">  
 <p>Do you have a name?</p>  
 <p><input type="text" name="NameBox" />  
    <input type="submit" value="Submit" /></p>  
</form>

Now, ASP.NET provides a set of special tags called Server Controls. We saw a simple sever control in the previous article in this line of code:

<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>

The <asp:label> tag here is an example of an ASP.NET Server Control. Server Controls are elements of ASP.NET Web pages (or as Microsoft calls them, Web Forms) that you can access with server-side code. In this case, our Page_Load script set the text of the <asp:label> tag to show the current time.

While some simple Server Controls such as <asp:label> exist for general use, the majority of Server Controls are for use in forms. The <asp:textbox> control, for example, is one of the most commonly used controls in ASP.NET. Here’s how our form looks once it has been modified to use an <asp:textbox> Server Control:

<form runat="server" id="NameForm">  
 <p>Do you have a name?</p>  
 <p><asp:textbox runat="server" id="NameBox" />  
    <input type="submit" value="Submit" /></p>  
</form>

You’ll notice that I’ve replaced the <input type="text"> tag with an <asp:textbox> tag. The runat="server" attribute tells ASP.NET that it’s responsible for turning the tag into something that Web browsers will understand. We’ve also changed the name attribute of the <input type="text"> tag into an id attribute, since ASP.NET Server Controls expect to be identified by their id.

You’ll also notice that I’ve changed the <form> tag slightly. Any form that contains ASP.NET Server Controls must have a runat="server" attribute, because ASP.NET needs to know not only about the Server Controls but also about the forms that they belong to. I’ve also assigned an id to the form so we can refer to it elsewhere in our code if we need to. The action attribute of the <form> tag has been removed entirely; ASP.NET takes care of adding it for us when it processes the <form> tag.

Let’s concentrate on the <asp:textbox> tag for now. By setting various attributes of <asp:textbox>, it can act as a server-side substitute for the HTML <input type="text"> and <textarea> tags. So basically any time you want users to type in text, <asp:textbox> is the tag to use. In this case, it acts just like an <input type="text"> tag, except that it has all the features of an ASP.NET Server Control (most importantly for our purposes, it can be accessed conveniently from our ASP.NET code).

Let’s slot this form code into our hellothere-cs.aspx file:

<%@ Page Language="C#" %>  
<html>  
<head>  
<title>My First ASP.NET Page</title>  
<script runat="server">  
 protected void Page_Load(Object Source, EventArgs E)  
 {  
   TimeLabel.Text = DateTime.Now.ToString();  
 }  
</script>  
</head>  
<body>  
 
<p>Hello there!</p>  
 
<form runat="server" id="NameForm">  
 <p>Do you have a name?</p>  
 <p><asp:textbox runat="server" id="NameBox" />  
    <input type="submit" value="Submit" /></p>  
</form>  
 
<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>  
 
</body>  
</html>

We’ll make one more change to the HTML of this page before we move on to processing the form submission. The greeting on the page is currently produced by this simple HTML code:

<p>Hello there!</p>

When the user provides a name, we want to replace the word ‘there’ with his or her name. We’ll make this possible by surrounding the word with an <asp:label> tag:

<p>Hello <asp:label runat="server" id="NameLabel">there  
</asp:label>!</p>

Previously, we used a self-closing <asp:label> tag (i.e. <asp:label ... />) for the TimeLabel to create a spot in the document where we could insert the current time. In this case, we’ve surrounded a segment of text (the word ‘there’) with an <asp:label> tag to mark a piece of the document that we can change.

You can think of ‘there’ as the default text to be displayed by the <asp:label> Server Control. In fact, if you prefer using a self-closing tag, you can specify the text (‘there’) as an attribute instead:

<p>Hello <asp:label runat="server" id="NameLabel" text="there" />!</p>

With our HTML code in place, let’s move on to the server-side script.

Processing a Simple Form

Form submissions in ASP.NET work a little differently than you might be used to. Rather than submitting to a different page, specified in the action attribute of the <form> tag, ASP.NET forms submit back to the same page. While you have the option of sending the browser to a different page in response to the form submission, the page with the form does need to handle the submission somehow.

Here is the code of our page so far:

<%@ Page Language="C#" %>   
<html>  
<head>  
<title>My First ASP.NET Form</title>  
<script runat="server">  
 protected void Page_Load(Object Source, EventArgs E)  
 {  
   TimeLabel.Text = DateTime.Now.ToString();  
 }
 
</script>  
</head>  
<body>  
 
<p>Hello <asp:label runat="server" id="NameLabel">  
there</asp:label>!</p>  
 
<form runat="server" id="NameForm">  
 <p>Do you have a name?</p>  
 <p><asp:textbox runat="server" id="NameBox" />  
    <input type="submit" value="Submit" /></p>  
</form>  
 
<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>  
 
</body>  
</html>

Right now, our server-side script (highlighted in bold above) simply sets the TimeLabel <asp:label> tag to display the current time whenever the page is loaded. We need to expand this script so that when the user submits the form, three things happen:

  • The form is hidden, since it is no longer needed.
  • The NameLabel <asp:label> tag’s text is set to the name provided by the user
  • The user’s name is displayed in bold.

In the Page_Load script, we can find out if the page was loaded as a result of a form submission by checking the IsPostBack property of the page. You see, when a form is posted (submitted) back to the same page that contains it, it’s called a post back. ASP.NET automatically supplies a property called IsPostBack that is true when the page is being loaded as a result of a post back, and is false otherwise.

So our expanded Page_Load script will take the following form if we use C# as the ASP.NET language for the page:

<script runat="server">   
 protected void Page_Load(Object Source, EventArgs E)  
 {  
   if (IsPostBack)  
   {  
     // Form processing code here ...  
   }
 
     
   TimeLabel.Text = DateTime.Now.ToString();  
 }  
</script>

The section in bold is an if statement. The code that appears between the curly braces will only be executed if the condition between the parentheses is true. So the form processing code will only be executed if the page is loading as a result of a post back. Note that since the code for setting the text of TimeLabel is outside the if statement, it will occur every time the page is loaded – not just for post backs.

Incidentally, in C#, lines that start with // are ignored. These are called comments, and let you write little notes to remind yourself of how the code works. In these articles, I’ll use comments to help you understand the code as I have above.

If you prefer VB.NET, it has an if statement as well, though the syntax is somewhat different:

<script runat="server">   
 Sub Page_Load(Source As Object, E As EventArgs)  
   If IsPostBack Then  
     ' Form processing code here ...  
   End If
 
     
   TimeLabel.Text = DateTime.Now.ToString()  
 End Sub  
</script>

You’ll also note that comments in VB.NET begin with an apostrophe (‘).

Okay, so we can now write code that happens when the page is the result of a post back. As your knowledge of ASP.NET improves you’ll be able to do things like store submitted values into a database, send an email containing the values from the form, or check if the user is allowed to access your site. For now, however, let’s add the code for the three simple things we want our example to do.

First, we need to hide the form. Since we assigned the form an id of NameForm in the HTML code of the page, we can do this very easily:

NameForm.Visible = false;

Next, we need to set the <asp:label> tag with id="NameLabel" to display the name submitted by the user. We already know how to set the text of an <asp:label> tag, but how do we get the name submitted by the user? Well, since the user typed the value into the <asp:textbox> with id="NameBox", the name can be accessed as NameBox.Text. So the to display the user’s name we just write:

NameLabel.Text = NameBox.Text;

Finally, we want to make the user’s name appear in bold to make him or her feel more important, and to highlight just how smart our page is! To do this, we will assign a Cascading Style Sheet (CSS) attribute to the NameLabel element that displays the user’s name. Here’s how it’s done:

NameLabel.Style.Add( "font-weight", "bold" );

The code for these three lines in VB.NET is actually identical to the C# versions we’ve just seen; just remove the semicolon from the end of each line.

Our finished page in C# is as follows:

<%@ Page Language="C#" %>    
<html>    
<head>    
<title>My First ASP.NET Form</title>    
<script runat="server">    
 protected void Page_Load(Object Source, EventArgs E)    
 {    
   if (IsPostBack)    
   {    
     NameForm.Visible = false;    
     NameLabel.Text = NameBox.Text;    
     NameLabel.Style.Add( "font-weight", "bold" );    
   }    
       
   TimeLabel.Text = DateTime.Now.ToString();    
 }    
</script>    
</head>    
<body>    
   
<p>Hello <asp:label runat="server" id="NameLabel">there    
</asp:label>!</p>    
   
<form runat="server" id="NameForm">    
 <p>Do you have a name?</p>    
 <p><asp:textbox runat="server" id="NameBox" />    
    <input type="submit" value="Submit" /></p>    
</form>    
   
<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>    
   
</body>    
</html>

And here’s the VB.NET version:

<%@ Page Language="VB" %>    
<html>    
<head>    
<title>My First ASP.NET Form</title>    
<script runat="server">    
 Sub Page_Load(Source As Object, E As EventArgs)    
   If IsPostBack Then    
     NameForm.Visible = false    
     NameLabel.Text = NameBox.Text    
     NameLabel.Style.Add( "font-weight", "bold" )    
   End If    
       
   TimeLabel.Text = DateTime.Now.ToString()    
 End Sub    
</script>    
</head>    
<body>    
   
<p>Hello <asp:label runat="server" id="NameLabel">there    
</asp:label>!</p>    
   
<form runat="server" id="NameForm">    
 <p>Do you have a name?</p>    
 <p><asp:textbox runat="server" id="NameBox" />    
    <input type="submit" value="Submit" /></p>    
</form>    
   
<p>The time is now: <asp:label runat="server" id="TimeLabel" /></p>    
   
</body>    
</html>

Save either of these and place it on your Web server. Load the page in your browser, and you’ll see the form as expected:

Submission Form

Type in your name and submit the form, and you’ll receive your personalized greeting!

Personalised Greeting

Be sure to take a minute to use the View Source feature of your browser to inspect the HTML code of each version of the page. Notice how the <asp:textbox> element in the form is actually sent to the browser as an ordinary <input type="text"> tag. Also notice that the form completely disappears once the name is submitted, and observe the style attribute that is generated to make the name bold.

The one part of the code you might not understand is the hidden __VIEWSTATE field that ASP.NET adds to the form. This is actually a pretty exciting ASP.NET feature, but it takes some explaining to understand, so you’ll have to wait until a later article in this series to find out about it.

Stay Tuned…

In my next article, I’ll demystify some of the object oriented programming concepts you need to understand to take full advantage of the .NET platform, including ASP.NET. I’ll teach you about classes, objects, properties, and methods, and then explain the concept of inheritance. Finally, we’ll use this concept to create an ASP.NET page where all the C# or VB.NET code is placed in a separate file, called a Code-Behind file.

Be sure to rate this article to let me know what you think!

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments