A Simple ASP.NET Application


Sams Teach Yourself ASP.NET in 21 Days, Second Edition
By Chris Payne
Table of Contents
Day 2.  Building ASP.NET Pages

Let's take another look at a code listing from yesterday. Listing 2.1 shows a simple page that takes the user's input and prints out a message saying "Hello". This simple page has a lot of interesting features that won't be discussed in depth until later in this book, but today you'll look at the overall picture.

Listing 2.1 Your First ASP.NET Page in VB.NET
 1:  <%@ Page Language="VB" %> 2: 3:  <script runat="server"> 4:     Sub tbMessage_Change(Sender As Object, E As EventArgs) 5:        lblMessage.Text = "Hello " + tbMessage.Text 6:     End Sub 7:  </script> 8: 9:  <html><body> 10:     <font size="5">Sam's Teach Yourself ASP.NET in 21 Days: 11:     Day 2</font><hr><p> 12:     <% Response.Write("Our First Page<p>") %> 13: 14:     <form runat="server"> 15:        Please enter your name: 16:        <asp:textbox  17:           OnTextChanged="tbMessage_Change" 18:           runat=server/> 19:        <asp:button  Text="Submit" 20:           runat=server/><p> 21:        <asp:label  font-size="20pt" 22:           runat=server/> 23:     </form> 24:  </body></html> 

Listing 2.2 shows the same page in C#.

Listing 2.2 Your First ASP.NET Page in C#
 1:  <%@ Page Language="C#" %> 2: 3:  <script runat="server"> 4:     void tbMessage_Change(Object Sender, EventArgs e) { 5:        lblMessage.Text = "Hello " + tbMessage.Text; 6:     } 7:  </script> 8: 9:  <html><body> 10:     <font size="5">Sam's Teach Yourself ASP.NET in 21 Days: 11:     Day 2</font><hr><p> 12:     <% Response.Write("Our First Page<p>"); %> 13: 14:     <form runat="server"> 15:        Please enter your name: 16:        <asp:textbox  17:           OnTextChanged="tbMessage_Change" 18:           runat=server/> 19:        <asp:button  Text="Submit" 20:           runat=server/><p> 21:        <asp:label  font-size="20pt" 22:           runat=server/> 23:     </form> 24:  </body></html> 

Before examining the details of the page, let's take a test drive. Open either listing in your browser (http://localhost/tyaspnet21days/day2/listing0201.aspx or listing0202.aspx). Type your name into the text box and click the Submit button. You should see "Hello [your name]" in large letters under the text box, similar to Figure 2.1. (Notice that the text you entered is still in the text box after you click Submit. You'll learn about this later today in the "Viewstate" section.)

Figure 2.1. The page produced by Listing 2.1.


Web Forms

If you know regular HTML, this page should look pretty familiar. On line 9 of either listing is the opening <html> and <body> tags, and the corresponding closing tags are at the end of the listing. There are some new tags in the form, so let's take a look at that section, shown in Listing 2.3.

Listing 2.3 The Form Section from Listing 2.1
 14:     <form runat="server"> 15:        Please enter your name: 16:        <asp:textbox  17:           OnTextChanged="tbMessage_Change" 18:           runat=server/> 19:        <asp:button  Text="Submit" 20:           runat=server/><p> 21:        <asp:label  font-size="20pt" 22:           runat=server/> 23:     </form> 


Notice that you didn't specify an action for the form. Normally, you would specify an action to tell an HTML form where to go to take care of the user input to process it or enter it into a database, for instance. If you don't specify the action, the form goes right back to itself. This is called a postback form because it posts back to itself. You can then include some ASP.NET code on this page to deal with the input.

ASP.NET uses postback forms extensively to process all of its user input. You'll become very familiar with this as you develop more pages.

The first new thing you'll notice is the runat keyword in the form tag. By specifying "server", you're instructing ASP.NET that you want to keep track of this form on the server. Recall from yesterday that the server has spies that alert it to what's happening on the client. This keyword links the visitor's input to what the server thinks is going on. Without this attribute, the form will act as a normal HTML form. If you view the source of this file from the Web browser, you'll see something like Listing 2.4.

Listing 2.4 Source from index.aspx
 1:  <form name="ctrl2" method="post" action="index.aspx" 2:     > 3:  <input type="hidden" name="__VIEWSTATE" 4:     value="YTB6LTEwNzAyOTU3NjJfX1949e1355cb" /> 

Not exactly what you typed in, is it? This will be explained further later today in "Viewstate." For now, just know that the ASP.NET engine inserts these HTML tags to help keep track of what's going on.


In case you're curious, specifying runat="client" in the <form> tag will not produce a normal HTML form. In fact, it will result in the error "Parser Error Message: The Runat attribute can only have the value 'Server'." If you want to create a regular HTML form, simply leave off the runat attribute.

Forms in ASP.NET that specify runat="server" are known as Web forms and are part of a framework that ASP.NET uses to provide much of the functionality for your applications. You'll learn more about these forms on Day 5, "Beginning Web Forms."

The next items of interest are the <asp:textbox>, <asp:button>, and <asp:label> tags. These are ASP.NET Web server controls, and each one has properties that you can use to provide functionality for your page. Again, if you view the source for this file from the Web browser, you'll see that the HTML equivalents of these ASP.NET controls are a text input, Submit button, and span tag, as shown in Listing 2.5.

Listing 2.5 Source from index.aspx
 1:  Please enter your name: 2:  <input name="tbMessage" type="text" value="Chris" 3:      /> 4:  <input type="submit" name="btSubmit" value="Submit" 5:      /><p> 6:  <span  style="font-size:20pt;">Hello 7:     Chris!</span> 

Also notice the id attribute in each of the controls. This is a unique name that you provide for the control so that you can reference it from other places in the page. For example, the label has the ID lblMessage. Further down the page, you could create some code that asks, "What is the text inside lblMessage?" (In fact, you'll do something similar to that in the <script> block.)


Don't forget to specify runat="server"! runat="server" is very important to ASP.NET pages. It tells ASP.NET that these items need to be processed on the server. Otherwise, ASP.NET would send the items straight to the client without any server interaction. And since browsers ignore any tags they don't understand, these items wouldn't be shown to the user. This is a very common mistake among ASP.NET beginners.


ASP.NET is very insistent about making the developer write strict code. This means that all tags should have opening and closing tags, such as <body>...</body> and <form>...</form>. Therefore, you should also see <asp:textbox>...</asp:textbox> as well.

However, here's a little shortcut. If you don't need to specify anything between the opening and closing tags, you can simply place a forward slash before the closing bracket, such as <asp:textbox />. Without the closing tag, ASP.NET will produce errors.


The text box you've built has another attribute, OnTextChanged="tbMessage_ Change". If you've worked with client-side scripting, this should look familiar. Your text box has an event called TextChanged. An event is something that occurs in your application, such as a mouse click or a selection change. The TextChanged event occurs when the content of the text box changes. By adding OnTextChanged="tbMessage_Change", you're telling ASP.NET to execute the tbMessage_Change procedure on the occurrence of the TextChanged event. Unlike client-side scripting, however, these events are handled by the server.

This is the basis for the event-driven model. Generally, ASP.NET applications simply respond to user input. A lot of the code in an ASP.NET page will be dedicated to handling such events, and you'll see these types of procedures very often.

Code Declaration Blocks

Considering the <script> block next, you can see the procedure in Listing 2.6.

Listing 2.6 The Script Block for Your First ASP.NET Page
 3:  <script runat="server"> 4:     Sub tbMessage_Change(Sender As Object, E As EventArgs) 5:        lblMessage.Text = "Hello " + tbMessage.Text 6:     End Sub 7:  </script> 

Again, if you're familiar with any form of scripting, you should recognize this section. The <script> tag is usually for client-side scripting. It delimits a section of the page that the application will process dynamically, called a code declaration block in ASP.NET. It isn't just rendered to the page like pure HTML, but contains programming code that should be executed by the computer. Don't forget to include runat="server"! Otherwise this code would be sent straight to the browser without being executed by ASP.NET.

Line 4 creates a Visual Basic subprocedure that performs some piece of functionality. From the analysis of Listing 2.3, you know that the text box uses this method when its TextChanged event occurs. There's a lot of syntax involved with this part, so we'll only cover the basics now. All you need to know is that whenever this procedure is called, it sets the Text property of the label named lblMessage to "Hello" plus the text of the text box, as shown on line 5. The result is that the page will now display "Hello [your name]!" The code (Sender As Object, E As EventArgs) on line 2 is a standard line that's required for most methods that handle events. This will be discussed in more detail on Days 5 and 6, and the Visual Basic code will be discussed tomorrow.

It's also important to use the runat="server" attribute to specify that the script block itself runs on the server. Otherwise, ASP.NET would treat it as client-side code, and it wouldn't produce the expected results. In this case ASP.NET would produce an error, as shown in Figure 2.2.

Figure 2.2. This error occurs if the runat="server" attribute isn't used.



You can actually place the <script> block anywhere in the page, but it's a good practice to separate it as much as possible from the presentation, or HTML, code. This makes it much easier to manage and debug your code if problems arise. Later you'll see how you can completely separate this code from this page altogether.

Code Render Blocks

Finally, let's look at line 12:

 12:  <% Response.Write("Our First Page<p>") %> 

This is a code render block. Between the <% and %> tags is VB code that the server processes before it sends the output to the browser. If you remove these tags, ASP.NET will treat the code as pure HTML and you'll get a page that looks like Figure 2.3.

Figure 2.3. The page from Figure 2.1 without the <% and %> tags.


Line 12 uses the Write method of the Response object to print out some text to the browser. You'll examine this object and its methods on Day 4, but for now you just need to know that it provides an easy way to write text dynamically to the browser.

If the output of Response.Write contains any HTML tags, the browser will interpret them as if they were plain HTML. For example, if you used the following, "Our First Page" would be rendered in bold characters:

 <% Response.Write("<b>Our First Page</b>") %> 

Notice that all the characters to be rendered are enclosed in quotation marks. This is a simple example, but the method can produce some interesting output, as you'll see on Day 4.


There's a shortcut to using Response.Write using the <%= tag. For example, the following two lines of code are equivalent:

 <% Response.Write("Hello") %> <% = "Hello" %> 

You may see this syntax interspersed throughout ASP.NET pages, so you should be aware of its existence.

The code render block is very similar to the code declaration block. You could even place this line in the <script> tags and it would work similarly. There are a few differences between line 12 and the <script> block, however. The first is that the code declaration block is compiled into machine code (by way of MSIL), which makes it faster and more stable than the code render block. The second difference is that each of these blocks is processed in a different order. If you moved line 12 into the code declaration block, you might not receive exactly the same output as when it's separate.

For these reasons, you'll be using code declaration blocks much more often than code render blocks throughout your ASP.NET pages. The render blocks were the staple of traditional ASP, but they've been replaced with better mechanisms in ASP.NET.

Page Directives

Line 1 of Listing 2.1 specified the following:

 1:  <%@ Page Language="VB" %> 

This is called a page directive. It allows you to include special instructions to ASP.NET on how to handle your pages. This page directive in particular tells ASP.NET that you'll be using Visual Basic as the default programming language on your page. You'll learn how to use other page directives throughout this book. Later today, in "Importing Namespaces," you'll learn about the import directive.

If you wanted to use C# as the default language for an ASP.NET page, you could use the following page directive:

 <%@ Page Language="C#" %> 

Day 4 will look at C# in more detail.

The Flow

Now that you know what the code looks like, what happens when someone requests the page from his Web browser?

The first time you request a page, ASP.NET compiles the code in the page's code declaration blocks. If you noticed a slight delay before the browser displayed the page, this is probably the cause. If you request the page a second time without changing any of the code, there won't be any delay. If you change the code even slightly, however, ASP.NET must recompile the page. Even though this results in a slight delay initially, it provides a tremendous increase in performance after the first request. So how does the engine know when the code changes?

Remember reading about managed code on Day 1? This ASP.NET page is precisely that some managed code that the Common Language Runtime is handling. The page is compiled into Microsoft Intermediate Language (MSIL), which is then compiled into native machine language when the page is requested. The actual source file that you created is stored separately, however, and the CLR keeps an eye on it. If it changes, the CLR recompiles the page.

Once the form is submitted and the code is compiled, ASP.NET starts to process all of the code you created and any events that have occurred. In this case, the TextChanged event occurred because you typed some text into the text box. The ASP.NET engine examines this event, determines what it should do, and does it.

ASP.NET then converts any server controls into HTML elements. For instance, it converts your <asp:TextBox> control into the HTML text input box. It then evaluates any of the code render blocks and outputs any HTML if necessary.

Finally, the resulting HTML is sent to the browser. The browser receives only standard, legal HTML ASP.NET doesn't send any code or server controls to the browser. Therefore, any Web browser can visit and properly render an ASP.NET page. As far as the Web browser's concerned, an ASP.NET page is simply an HTML page with a slightly different extension. For instance, Figure 2.4 shows the HTML received by the browser.

Figure 2.4. The HTML source code received by the browser from Listing 2.1.


This is an important concept to grasp. The browser is a dumb application, in a sense. It can only interpret HTML, and that's it. ASP.NET knows this, so anything that needs to be sent to the browser is converted into HTML. Luckily, ASP.NET is sneaky, and it knows ways to trick HTML into doing some processing as well. You'll learn more about this on Day 5.

Figure 2.5 outlines the workflow for a typical ASP.NET page.

Figure 2.5. The ASP.NET workflow, from request to display.


This, in a nutshell, is how ASP.NET pages are processed and delivered.


The viewstate describes how an object looks at that particular moment. For example, the viewstate for the text box shown in Figure 2.1 contains the text "Chris", the viewstate for a button indicates whether or not it's being clicked, and so on. An application that keeps track of this information is said to maintain state.

If you fill out an HTML form and come back to it later, chances are the fields you've filled out will be empty. This is because the Web is a stateless medium it doesn't allow you to keep track of viewstate or other such information. This was often a pain for traditional ASP developers because it required mechanisms to maintain and retrieve this information. ASP.NET makes this much easier.

ASP.NET automatically keeps track of the viewstate for you. This means that if you fill out an HTML form and click Submit, the values will still be there when the page comes back! This is an important part of ASP.NET and is integral to a number of different mechanisms.

ASP.NET does this by outputting hidden HTML form fields whenever you tell a form runat="server". Remember the hidden field on line 3 of Listing 2.4? That string of seemingly random characters is ASP.NET's way of telling itself what each control looks like. When the form is submitted, ASP.NET automatically retrieves this string and uses it to fill out the form information again. ASP.NET uses the fact that browsers can only understand HTML and writes itself reminders in the pages that are sent to the client.

For example, look at the following line written on the server:

 <form runat="server"> 

This sends the following HTML code to the browser:

 <form name="ctrl2" method="post" action="listing0201.aspx"    > <input type="hidden" name="__VIEWSTATE"    value="YTB6LTEwNzAyOTU3NjJfX1949e1355cb" /> 

Viewstate management showcases ASP.NET's focus on making the Web a more traditional application environment.


    Sams Teach Yourself ASP. NET in 21 Days
    Sams Teach Yourself ASP.NET in 21 Days (2nd Edition)
    ISBN: 0672324458
    EAN: 2147483647
    Year: 2003
    Pages: 307
    Authors: Chris Payne

    Similar book on Amazon

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net