Examining the Source Code Portion of an ASP.NET Web Page


Now that we've examined the HTML portion of an ASP.NET web page, let's turn our attention to the source code portion. While the HTML portion defines the layout of the ASP.NET page along with its static content, it's the source code portion where the content for the dynamic portions of the page is decided.

The source code portion for ASP.NET pages can appear in one of two locations:

  • In a separate file The ASP.NET page is composed of two separate files, PageName.aspx and PageName.aspx.vb. The PageName.aspx file contains the HTML and Web control syntax, while the PageName.aspx.vb file contains the source code. This is how our current sample web page is structured, with Default.aspx and Default.aspx.vb.

  • In a <script> block in the same file The HTML and source code portions can reside in the same, single file. In this scenario, the source code portion is placed within a server-side <script> block.

The examples in this book use the separate file technique, although either option is acceptable. Many developers prefer the separate file approach because it provides a cleaner separation between the HTML and source code portions. Furthermore, in the previous version of ASP.NET, there were several other advantages to using a separate file over the server-side <script> block.

If you find yourself working in a large ASP.NET project, you'll more than likely be using the separate file approach. Hence, we'll stick with this technique for the examples in this book.

By the Way

ASP.NET web pages can have their source code portion written in one of two programming languages: Visual Basic or Visual C#. In this book all of our code examples will use Visual Basic.

For more information on Visual Basic, consult Hours 5 through 7.


You can view the source code portion of an ASP.NET page that uses the separate file technique through any one of the following actions:

  • Right-click on the ASP.NET page in the Solution Explorer and choose View Code.

  • Click on the plus icon in the Solution Explorer for the ASP.NET page whose source code you want to edit. This will list its corresponding source code file, PageName.aspx.vb. Double-click on this source code file to display its contents.

  • In the Source or Design view of an ASP.NET page, right-click and choose View Code.

Take a moment to view the source code portion for Default.aspx. You should find the following content in Default.aspx.vb:

Partial Class _Default     Inherits System.Web.UI.Page End Class 


These three lines are the bare minimum code that must exist in an ASP.NET page's source code portion. Specifically, it's defining a class called Default that extends the System.Web.UI.Page class. Classes are a central construct of object-oriented programming, which is the programming paradigm used by ASP.NET. The next few sections provide an overview of object-oriented and event-driven programming; if you are already familiar with these concepts, feel free to skip ahead to the "Event Handlers in ASP.NET" section.

By the Way

It is vitally important to remember that the ASP.NET page's source code portion is server-side code. As we discussed in Hour 1, "Getting Started with ASP.NET 2.0," when an ASP.NET page is requested, the ASP.NET engine executes the source code and returns the resulting HTML to the requesting browser. Therefore, none of the ASP.NET page's source code is sent to the browser, just the resulting markup.


A Quick Object-Oriented Programming Primer

The source code portion of an ASP.NET web page uses a particular programming model known as object-oriented programming. Object-oriented programming is a programming paradigm that generalizes programming in terms of objects. A key construct of any object-oriented programming language is the class, which is used to abstractly define an object. Classes contain properties, which describe the state of the object; methods, which provide the actions that can be performed on the object; and events, which are actions triggered by the object. Objects are instances of classes, representing a concrete instance of an abstraction.

Whew! This all likely sounds very confusing, but a real-world analogy should help. Think, for a moment, about a car. What things describe a car? What actions can a car perform? What events transpire during the operation of a car?

A car can have various properties, like its make, model, year, and color. A car also has a number of actions it can perform, such as drive, reverse, turn, and park. While you're driving a car, various events occur, such as stepping on the brakes and turning on the windshield wipers.

By the Way

In object-oriented terms, an object's actions are referred to as its methods.


This assimilation of properties, actions, (hereby referred to as methods), and events abstractly defines what a car can do. The reason this assimilation of properties and methods is an abstraction is that it does not define a specific car; rather, it describes features common to all cars. This collection of properties, methods, and events describing an abstract car is a class in object-oriented terms.

An object is a specific instance of a class. In our analogy, an object would be a specific instance of the car abstraction, such as a year 2000, forest green, Honda Accord. The methods of the car abstraction can then be applied to the object. For example, to drive this Honda to the store, I'd use the Drive method, applying the Turn method as needed. When I reached the store, I'd use the Park method. After making my purchases, I'd need to back out of the parking spot, so I'd use the Reverse method, and then the Drive and Turn methods to get back home. During the operation of the car object, various events might occur: When I'm driving to the store, the "Turning the steering wheel" event will more than likely transpire, as will the "Stepping on the brakes" event.

Examining Event-Driven Programming

Another important construct of the programming languages used to create ASP.NET web pages is the event handler. An event, as we just saw, is some action that occurs during the use of an object. An event handler is a piece of code that is executed when its corresponding event occurs. Programming languages that include support for handling events are called event-driven.

By the Way

When an event occurs, it commonly is said that the event has fired or been raised. Furthermore, an event handler, when run, is referred to as having been executed. Therefore, when an event fires (or is raised), its event handler executes.


For events to be useful, they need to be paired with an event handler. An event handler is a block of source code that is executed when the event it is specified to handle fires. The event handler for the car's Starting event, for example, might contain code that instructs the starter to start turning the crankshaft. When the stepping on the brakes event fires, code might execute that applied the brake pads to the brake drums.

You can think of ASP.NET web pages as event-driven programs. The source code portion of the ASP.NET web page is made up of event handlers. Furthermore, a number of potential events can fire during the rendering of an ASP.NET page.

Out-of-Order Execution

In ASP or PHP, two other dynamic web page technologies, the source code portion of a web page is executed serially, from top to bottom. That is, if the source code section contains five lines of code, the first line of code is executed first, followed by the second, then the third, the fourth, and finally the fifth. This programming paradigm, in which one line of code is executed after another, is known as sequential execution. With sequential execution, the code is executed from the first line of code to the last. With sequential execution, you know that code on line 5 will execute before code on line 10.

With event-driven programming, however, there are no such guarantees. The only serial portions of code in an event-driven program are those lines of code within a particular event handler. Often you can't make any assumptions on the order that the events will fire, and therefore you can't be certain the order with which the corresponding event handlers will be called. Furthermore, often you can't assume that a particular event will fire at all.

Looking back at our car analogy, imagine that our car has the following events:

  • Starting

  • Stopping

  • Applying brakes

  • Starting windshield wipers

During a car's usedriving from home to the store, let's saysome events will definitely fire, such as the Starting and Stopping events. However others, such as "Starting windshield wipers," might not fire at all. Furthermore, while we can assume that the Starting event will be the first event to fire and Stopping the last, we can't say with any certainty whether or not the "Applying brakes" event will come before or after the "Starting windshield wipers" event.

When creating an ASP.NET page, you may optionally create event handlers for the plethora of events that may transpire during the ASP.NET page's life cycle. When an event fires, its corresponding event handlerif definedexecutes. Returning to the car analogy, we may want to have event handlers for just the Starting and Stopping events. The code in the event handlers would be executed when the corresponding events fired. For example, imagine that our Starting event has an event handler that had the following two lines of code:

Begin Starting Event Handler   Send signal to starter to start turning the crankshaft   Send signal to fuel injector to send fuel to the engine End Starting Event Handler 


When the Starting event fires, the Starting event handler is executed. The first line of code in this event handler will fire first, followed by the second. Our complete source code for the car may consist of two event handlers, one for Starting and one for Stopping.

Begin Starting Event Handler   Send signal to starter to start turning the crankshaft   Send signal to fuel injector to send fuel to the engine End Starting Event Handler Begin Stopping Event Handler   Send signal to brake drums   Decrease fuel injector's output End Stopping Event Handler 


Even though the Starting event handler appears before the Stopping event handler in the source code, this does not imply that the Starting event handler will execute prior to the Stopping event handler. Because the event handlers are executed only when their corresponding event fires, the order of execution of these event handlers is directly dependent on the order of the events that are fired.

The important point to keep in mind is that the order of the event handlers in the source code has no bearing on the order of execution of the event handlers.

By the Way

The code used to describe the Starting and Stopping events is not actual Visual Basic code, but is instead pseudocode. Pseudocode is not code recognized by any particular programming language, but instead is a made-up, verbose, English-like language commonly used when describing programming concepts.


Event Handlers in ASP.NET

When writing the code for an ASP.NET page's source code portion, you'll be creating event handlers that execute in response to a specific ASP.NET-related event. One example of an ASP.NET event is the page's Load event, which fires every time an ASP.NET page is requested. If you have code that you want executed each time the page is requested, you can create an event handler for the Load event and place this code there.

There are a couple of ways to create the event handler for the Load event:

  • If you are viewing the ASP.NET page's HTML portion through the Design view, you can simply double-click somewhere in the Designer background. Just be sure to double-click the background, and not some existing Web control (like a Button or Image tag). If you double-click a Web control you'll create an event handler for one of the events of that Web control.

  • From the source code portion, you'll find two drop-down lists at the top. From the left drop-down list, select (Page Events). Then, from the right drop-down list, select Load (see Figure 2.11).

    Figure 2.11. You can create the page's Load event handler from the drop-down lists.

  • Lastly, you can simply type in the necessary event handler syntax for creating the event handler and associating it with the page's Load event.

Regardless of how you create the event handler, once you have done so, the syntax in your source code portion should resemble that in Listing 2.4.

Listing 2.4. The Page_Load Event Handler Fires in Response to the Page's Load Event

[View full width]

1: Partial Class _Default 2:     Inherits System.Web.UI.Page 3: 4:     Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)  Handles Me.Load 5: 6:     End Sub 7: End Class 

Whenever the ASP.NET page is visited through a browser, whatever code you add between lines 4 and 6 will be executed.

Watch Out!

You should not type the line numbers shown in Listing 2.4 into the source code portion. These line numbers are present simply to make it easier to refer to specific lines of code in the listing.


As we will see in future hours, many events can fire during the rendering of an ASP.NET web page. In addition to page-level events (such as the Load event), Web controls have associated events as well. For example, one of the ASP.NET Web controls is the Button Web control. When the user visiting the web page clicks the Button Web control, the button's Click event is fired; if an event handler is created for this event, the code within that event handler will execute upon the button being clicked. For now, though, we'll be working strictly with the page's Load event.

Programmatically Working with Web Controls

Earlier this hour, I mentioned that one difference between Web controls and static HTML content was that Web controls could be programmatically accessed, whereas static HTML content cannot. Furthermore, Web controls have a number of properties; for example, the Image Web controls added earlier had the ImageUrl property that indicated the URL of each search engine's logo. These properties can be read from and written to in the ASP.NET page's source code portion.

To illustrate this concept, let's enhance Default.aspx to contain some dynamic text at the top of the page. Specifically, above the <table> of search engine names and logos, let's add text that says, "Welcome to my site, it is now currentTime," where currentTime is the current date and time on the web server. (The web server in this instance is your personal computer.)

To accomplish this, return to Default.aspx and add a Label Web control above the HTML <table>. A Label Web control is designed to display dynamic text in an ASP.NET page and is covered in greater detail in Hour 8, "ASP.NET Web Controls for Displaying Text." To add the Label Web control, you can either drag on the control from the Toolbox through the Design or Source views or, if you'd rather, enter the following syntax in the Source view by hand before the <table> element:

<asp:Label  runat="server" Text="Label"></asp:Label> 


Once you've added the Label, change its Text and ID properties. Recall that this can be accomplished through the Properties window; if you are in the Source view, it may be quicker to just edit the attributes value directly in the HTML markup as opposed to using the Properties window, although either approach will suffice.

Specifically, clear out the Text property and change the ID to currentTime. Figure 2.12 shows the Properties window after these changes have been made.

Figure 2.12. The Label's ID and Text properties have been altered.


Once this change has been made, the syntax for the Label Web control in the Source view should now look like so:

<asp:Label  runat="server"></asp:Label> 


In the source code portion of this ASP.NET page, we're going to programmatically set the Text property of the currentTime Label Web control to the current date and time. To accomplish this, return to the source code portion and, in the Page_Load event handler added earlier, enter the following line of code (referring back to Listing 2.4, you would add this on line 5):

currentTime.Text = "Welcome to my site, it is now " & DateTime.Now 


Note that the Web control is referenced programmatically by its ID property value. That is, our Label Web control's ID property was set to currentTime; hence, we can programmatically set its properties using currentTime.Property.

Did you Know?

When you type currentTime into the source code view and follow it with a period (.), Visual Web Developer displays the set of available properties and methods for this Web control. This listing of available properties and methods is known as IntelliSense, and it saves oodles of time!

When viewing the drop-down list of allowable properties and methods, you can just type in the first few letters of the property or method you want to select. When the property or method you want to use is highlighted in the drop-down list, simply press the Tab key and Visual Web Developer will type in the rest for you.

If you do not see a drop-down list after entering currentTime and typing a period, Visual Web Developer could not find a suitably named Web control in the ASP.NET page's HTML portion. Take a moment to ensure that the Label Web control's ID property is, indeed, currentTime.


Take a moment to view Default.aspx tHRough a browser (see Figure 2.13). Now, at the top of your page, you'll find the message "Welcome to my site, it is now currentTime." If you refresh your browser, the currentTime displayed will be updated. This illustrates the dynamic nature of ASP.NET pages, as we now have a page whose content is not static, but rather based on the current date and time.

Figure 2.13. The ASP.NET page shows the current date and time.


As this example illustrated, a Web control's properties can be set either declaratively (via markup) or programmatically (via code). When a Web control property is specified through the Properties window or in the Web control syntax in the HTML portion, the property is said to be declaratively set. The ID property in our current example was set declaratively, as were the ImageUrl properties of the Image Web controls in the example that preceded this one. When the property value is set through the source code portion, it is said to have been set programmatically. In this example we set the Label's Text property programmatically.




Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

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