ASP 101 - Active Server Pages 101 - Web01
The Place ASP Developers Go!



Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates
ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash



 Top ASP 101 Stories Top ASP 101 Stories
The Top 10 ASP Links @ Microsoft.com
What is Adovbs.inc and Why Do I Need It?
An Overview of ASP.NET

QUICK TIP:
Hiding and restoring Visual InterDev's Workspace pane
Show All Tips >>
ASP 101 RSS Feed ASP 101 Updates


Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition

from SitePoint

Chapter 2: ASP.NET Basics

So far, you've learned what ASP.NET is, and what it can do. You've installed the software you need to get going, and, having been introduced to some very simple form processing techniques, you even know how to create a simple ASP.NET page. Don't worry if it all seems a little bewildering right now, because, as this book progresses, you'll learn how to use ASP.NET at more advanced levels.

As the next few chapters unfold, we'll explore some more advanced topics, including the use of controls, and various programming techniques. But before you can begin to develop applications with ASP.NET, you'll need to understand the inner workings of a typical ASP.NET page--with this knowledge, you'll be able to identify the parts of the ASP.NET page referenced in the examples we'll discuss throughout this book. So, in this chapter, we'll talk about some key mechanisms of an ASP.NET page, specifically:

  • page structure
  • view state
  • namespaces
  • directives

We'll also cover two of the "built-in" languages supported by the .NET Framework: VB and C#. As this section progresses, we'll explore the differences and similarities between these two languages, and get a clear idea of the power that they provide to those creating ASP.NET applications.

So, what exactly makes up an ASP.NET page? The next few sections will give you an in-depth understanding of the constructs of a typical ASP.NET page.

ASP.NET Page Structure

ASP.NET pages are simply text files that have the .aspx file name extension, and can be placed on any web server equipped with ASP.NET.

When a client requests an ASP.NET page, the web server passes the page to the ASP.NET runtime, a program that runs on the web server that's responsible for reading the page and compiling it into a .NET class. This class is then used to produce the HTML that's sent back to the user. Each subsequent request for this page avoids the compilation process: the .NET class can respond directly to the request, producing the page's HTML and sending it to the client, until such time as the .aspx file changes. This process is illustrated in Figure 2.1.

An ASP.NET page consists of the following elements:

  • directives
  • code declaration blocks
  • code render blocks
  • ASP.NET server controls
  • server-side comments
  • literal text and HTML tags

Figure 2.2 illustrates the various parts of a simple ASP.NET page.

1556_fig-aspnetpagelifecycle
Figure 2.1. The life cycle of the ASP.NET page

1556_fig-partsofaspnetpage
Figure 2.2. The parts of an ASP.NET page

To make sure we're on the same page and that the code works, save this piece of code in a file named Hello.aspx within the Learning virtual directory you created in Chapter 1. Loading the file through http://localhost/Learning/Hello.aspx should render the result shown in Figure 2.3.

1556_0210_HelloWorld
Figure 2.3. Sample Page in action

As you can see, this ASP.NET page contains examples of all the above components (except server-side includes) that make up an ASP.NET page. You won't often use every single element in a given page, but it's important that you are familiar with these elements, their purposes, and how and when it's appropriate to use them.

Directives

The directives section is one of the most important parts of an ASP.NET page. Directives control how a page is compiled, specify how a page is cached by web browsers, aid debugging (error-fixing), and allow you to import classes to use within your page's code. Each directive starts with <%@. This is followed by the directive name, plus any attributes and their corresponding values. The directive then ends with %>.

There are many directives that you can use within your pages, and we'll discuss them in greater detail later, but, for now, know that the Import and Page directives are the most useful for ASP.NET development. Looking at the sample ASP.NET page in Figure 2.2, we can see that a Page directive was used at the top of the page like so:

Example 2.1. Hello.aspx (excerpt)

<%@ Page Language="VB" %>

Example 2.2. Hello.aspx (excerpt)

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

In this case, the Page directive specifies the language that's to be used for the application logic by setting the Language attribute. The value provided for this attribute, which appears in quotes, specifies that we're using either VB or C#. A whole range of different directives is available; we'll see a few more later in this chapter.

Unlike ASP, ASP.NET directives can appear anywhere on a page, but they're commonly included at its very beginning.

Code Declaration Blocks

In Chapter 3, VB and C# Programming Basics, we'll talk about code-behind pages and how they let us separate our application logic from an ASP.NET page's HTML. However, if you're not working with code-behind pages, you must use code declaration blocks to contain all the application logic of your ASP.NET page. This application logic defines variables, subroutines, functions, and more. In our page, we've placed the code inside <script> tags, like so:

<script runat="server">
 Sub mySub()
   ' Code here
 End Sub
</script>

Here, the tags enclose VB code, but it could just as easily be C#:

<script runat="server">
 void mySub()  
 {
   // Code here
 }
</script>

Comments in VB and C# Code

Both of these code snippets contain comments--explanatory text that will be ignored by ASP.NET, but which serves to describe to us how the code works.

In VB code, a single quote or apostrophe (') indicates that the remainder of the line is to be ignored as a comment.

In C# code, two slashes (//) achieve the same end. C# code also lets us span a comment over multiple lines if we begin it with /* and end it with */, as in this example:

<script runat="server">
 void mySub()  
 {
   /* Multi-line
      comment    */
 }
</script>

Before .NET emerged, ASP also supported such script tags using a runat="server" attribute. However, they could only ever contain VBScript and, for a variety of reasons, they failed to find favor among developers.

Code declaration blocks are generally placed inside the head of your ASP.NET page. The sample ASP.NET page shown in Figure 2.2, for instance, contains the following code declaration block:

Example 2.3. Hello.aspx (excerpt)

<script runat="server">
 Sub Page_Load()
   messageLabel.Text = "Hello World"
 End Sub
</script>

Perhaps you can work out what the equivalent C# code would be:

Example 2.4. Hello.aspx (excerpt)

<script runat="server">
 void Page_Load()  
 {
   messageLabel.Text = "Hello World";
 }
</script>

The <script runat="server"> tag also accepts two other attributes. We can set the language that's used in this code declaration block via the language attribute:

<script runat="server" language="VB">

<script runat="server" language="C#">

If you don't specify a language within the code declaration block, the ASP.NET page will use the language provided by the language attribute of the Page directive. Each page's code must be written in a single language; for instance, it's not possible to mix VB and C# in the same page.

The second attribute that's available to us is src; this lets us specify an external code file for use within the ASP.NET page:

<script runat="server" language="VB" src="mycodefile.vb">

<script runat="server" language="C#" src="mycodefile.cs">

Code Render Blocks

If you've had experience with traditional ASP, you might recognize these blocks. You can use code render blocks to define inline code or expressions that will execute when a page is rendered. Code within a code render block is executed immediately when it is encountered--usually when the page is loaded or rendered. On the other hand, code within a code declaration block (within <script> tags) is executed only when it is called or triggered by user or page interactions. There are two types of code render blocks?inline code, and inline expressions--both of which are typically written within the body of the ASP.NET page.

Inline code render blocks execute one or more statements, and are placed directly inside a page's HTML between <% and %> delimiters. In our example, the following is a code render block:

Example 2.5. Hello.aspx (excerpt)

<% Dim Title As String = "This is generated by a code render " & _
   "block." %>

Example 2.6. Hello.aspx (excerpt)

<% string Title = "This is generated by a code render block."; %>

These code blocks simply declare a String variable called Title, and assign it the value This is generated by a code render block.

Inline expression render blocks can be compared to Response.Write in classic ASP. They start with <%= and end with %>, and are used to display the values of variables and methods on a page. In our example, an inline expression appears immediately after our inline code block:

Example 2.7. Hello.aspx (excerpt)

<%= Title %>

If you're familiar with classic ASP, you'll know what this code does: it simply outputs the value of the variable Title that we declared in the previous inline code block.

ASP.NET Server Controls

At the heart of any ASP.NET page lie server controls, which represent dynamic elements with which your users can interact. There are three basic types of server control: ASP.NET controls, HTML controls, and web user controls.

Usually, an ASP.NET control must reside within a <form runat="server"> tag in order to function correctly.

Controls offer the following advantages to ASP.NET developers:

  • They give us the ability to access HTML elements easily from within our code: we can change these elements' characteristics, check their values, or even update them dynamically from our server-side programming language of choice.
  • ASP.NET controls retain their properties thanks to a mechanism called view state. We'll be covering view state later in this chapter. For now, you need to know that view state prevents users from losing the data they've entered into a form once that form has been sent to the server for processing. When the response comes back to the client, text box entries, drop-down list selections, and so on, are all retained through view state.
  • With ASP.NET controls, developers are able to separate a page's presentational elements (everything the user sees) from its application logic (the dynamic portions of the ASP.NET page), so that each can be considered separately.
  • Many ASP.NET controls can be "bound" to the data sources from which they will extract data for display with minimal (if any) coding effort.

ASP.NET is all about controls, so we'll be discussing them in greater detail as we move through this book. In particular, Chapter 4, Constructing ASP.NET Web Pages explains many of the controls that ship with ASP.NET. For now, though, let's continue with our dissection of an ASP.NET page.

Server-side Comments

Server-side comments allow you to include within the page comments or notes that will not be processed by ASP.NET. Traditional HTML uses the <!-- and --> character sequences to delimit comments; any information included between these tags will not be displayed to the user. ASP.NET comments look very similar, but use the sequences <%-- and --%>.

Our ASP.NET example contains the following server-side comment block:

Example 2.8. Hello.aspx (excerpt)

<%-- Declare the title as string and set it --%>

The difference between ASP.NET comments and HTML comments is that ASP.NET comments are not sent to the client at all; HTML comments are, so they're not suited to commenting out ASP.NET code. Consider the following example:

<!--
<% string Title = "This is generated by a code render block."; %>
<%= Title %>
-->

Here, it looks as if a developer has attempted to use an HTML comment to stop a code render block from being executed. Unfortunately, HTML comments will only hide information from the browser, not the ASP.NET runtime. So, in this case, while we won't see anything in the browser that represents these two lines, they will be processed by ASP.NET, and the value of the variable Title will be sent to the browser inside an HTML comment, as shown here:

<!--

This code generated by a code render block.
-->

The code could be modified to use server-side comments very simply:

<%--  
<% string Title = "This is generated by a code render block."; %>
<%= Title %>
--%>

The ASP.NET runtime will ignore the contents of this comment, and the value of the Title variable will not be output.

Literal Text and HTML Tags

The final elements of an ASP.NET page are plain old text and HTML. Generally, you can't do without these elements?after all, HTML allows the display of the information in your ASP.NET controls and code in a way that's suitable for users. Let's take a look at the literal text and HTML tags that were used to produce the display in Figure 2.2:

Example 2.9. Hello.aspx (excerpt)

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Sample Page</title>
   <script runat="server">
     Sub Page_Load()
       messageLabel.Text = "Hello World!"
     End Sub
   </script>
 </head>
 <body>

   <form runat="server">
     <p>
       <asp:Label id="messageLabel" runat="server" />
     </p>
     <p>
       <%-- Declare the title as string and set it --%>
       <% Dim Title As String = "This is generated by a " & _
           "code render block." %>
       <%= Title %>
     </p>
   </form>
 </body>
</html>

Example 2.10. Hello.aspx (excerpt)

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Sample Page</title>

   <script runat="server">
     void Page_Load()  
     {
       messageLabel.Text = "Hello World";
     }
   </script>
 </head>
 <body>

   <form runat="server">
     <p>
       <asp:Label id="messageLabel" runat="server" />
     </p>
     <p>
       <%-- Declare the title as string and set it --%>
       <% string Title = "This is generated by a code render " +
           "block."; %>
       <%= Title %>
     </p>
   </form>
 </body>
</html>

The bold code above highlights the fact that literal text and HTML tags provide the structure for presenting our dynamic data. Without these elements, this page would have no format, and the browser would be unable to understand it.

You now have a clearer understanding of the structure of an ASP.NET page. As you work through the examples in this book, you'll begin to realize that, in many cases, you won't need to use all of these elements. For the most part, your development will be modularized within code declaration blocks, and all of the dynamic portions of your pages will be contained within code render blocks or controls located inside a <form runat="server">> tag.

In the following sections, we'll explore view state, discuss working with directives, and shine a little light on the languages that can be used within ASP.NET.

View State

As we saw briefly in the previous section, ASP.NET controls automatically retain their data when a page is sent to the server in response to an event (such as a user clicking a button). Microsoft calls this persistence of data "view state." In the past, developers would have had to use hacks to remember the item a user had selected in a drop-down menu, or store the content entered into a text box; typically, these hacks would have relied on hidden form fields.

This is no longer the case: once they're submitted to the server for processing, ASP.NET pages automatically retain all the information contained in text boxes and drop-down lists, as well as radio button and checkbox selections. They even keep track of dynamically generated tags, controls, and text. Consider the following ASP (not ASP.NET!) page, called Sample.asp:

Example 2.11. Sample.asp

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>Sample Page using VBScript</title>
 </head>
 <body>
   <form method="post" action="sample.asp">
     <input type="text" name="nameTextBox"/>
     <input type="submit" name="submitButton"
         value="Click Me" />
     <%
     If Request.Form("nameTextBox") <> "" Then
       Response.Write(Request.Form("nameTextBox"))
     End If
     %>
   </form>
 </body>
</html>

Cassini and ASP
Cassini is an ASP.NET-only web server and will not execute pages written in ASP, such as Sample.asp above. Fortunately, this won't be a problem as you work your way through this book, as the above Sample.asp file is the only ASP code in this book.

If you save this as Sample.asp in the Learning virtual directory you created in Chapter 1, Introducing ASP.NET and the .NET Platform, and open it in your browser by entering http://localhost/Learning/Sample.asp, you'll see that view state is not automatically preserved. When the user submits the form, the information that was typed into the text box is cleared, although it's still available in Request.Form("nameTextBox"). The equivalent page in ASP.NET, ViewState.aspx, demonstrates this data persistence using view state:

Example 2.12. ViewState.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>View State Example</title>
   <script runat="server" language="VB">
     Sub Click(s As Object, e As EventArgs)
       messageLabel.Text = nameTextBox.Text
     End Sub
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:TextBox id="nameTextBox" runat="server" />
     <asp:Button id="submitButton" runat="server"
         Text="Click Me" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

Example 2.13. ViewState.aspx

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
 <head>
   <title>View State Example</title>
   <script runat="server" language="C#">
     void Click(Object s, EventArgs e)  
     {
       messageLabel.Text = nameTextBox.Text;
     }
   </script>
 </head>
 <body>
   <form runat="server">
     <asp:TextBox id="nameTextBox" runat="server" />
     <asp:Button id="submitButton" runat="server"
         Text="Click Me" OnClick="Click" />
     <asp:Label id="messageLabel" runat="server" />
   </form>
 </body>
</html>

In this case, the code uses ASP.NET controls with the runat="server" attribute. As you can see in Figure 2.4, the text from the box appears on the page when the button is clicked, but also notice that the data remains in the text box! The data in this example is preserved by view state.

1556_0215_ViewState
Figure 2.4. ASP.NET maintaining the state of the controls

You can see the benefits of view state already. But where's all that information stored? ASP.NET pages maintain view state by encrypting the data within a hidden form field. View the source of the page after you've submitted the form, and look for the following code:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
   value="/wEPDwUKLTEwNDY1Nzg0MQ9...0fMCR+FN5P6v5pkTQwNEl5xhBk" />

This is a standard HTML hidden form field. All information that's relevant to the view state of the page is stored within this hidden form field as an encrypted string.

View state is enabled for every page by default. If you do not intend to use view state, you can turn it off, which will result in a slight performance gain in your pages. To do this, set the EnableViewState property of the Page directive to false:

<%@ Page EnableViewState="False" %>

Disabling View State, Control by Control
View state can also be disabled for particular controls in a page: simply set their EnableViewState property to false. We'll see working examples of this in the following chapters.

Speaking of directives, it's time to take a closer look at these curious beasts!

Working with Directives

For the most part, ASP.NET pages resemble traditional HTML pages with a few additions. In essence, just using the .aspx extension for an HTML file will ensure that IIS passes the page to the .NET Framework for processing. However, before you can work with certain, more advanced features, you'll need to know how to use directives.

We talked a little about directives and what they can do earlier in this chapter. You learned that directives control how a page is created, how a page is cached, help with bug-fixing, and allow us to import advanced functionality for use within our code. Three of the most commonly used directives are:

Page - This directive defines page-specific attributes for the ASP.NET page, such as the language used for server-side code. We've already seen this directive in use.

Import - The Import directive makes functionality that's been defined elsewhere available in a given page. The following example, for instance, imports functionality from the System.Web.Mail namespace, which you could use to send email from a page. Namespaces are simply .NET's way of keeping all its functionality neatly organized?we'll see how they work in Chapter 3.

<%@ Import Namespace="System.Web.Mail" %>

You'll become very familiar with this directive as you work through this book.

Register - This directive allows you to register a user control for use on your page. We'll cover Register in detail in Chapter 4, but the directive looks something like this:

<%@ Register TagPrefix="uc" TagName="footer"
   Src="footer.ascx" %>

ASP.NET Languages

As we saw in the previous chapter, .NET supports many different languages; in fact, there's no limit to the number of languages that could be supported. If you're used to writing ASP, you may think the choice of VBScript or JScript would be an obvious one. But, with ASP.NET, Microsoft did away with VBScript, merging it with Visual Basic. ASP.NET's support for C# is likely to find favor with developers from other backgrounds. This section will introduce you to both these new languages, which will be covered in more depth in the next chapter. By the end of this section, you will, I hope, agree that the similarities between the two are astonishing?any differences are minor and, in most cases, easy to figure out.

Traditional server technologies are much more constrained in terms of the development languages they offer. For instance, old-style CGI scripts were typically written with Perl or C/C++, JSP uses Java, Coldfusion uses CFML, and PHP is a technology and a language rolled into one. .NET's support for many different languages lets developers choose the ones they prefer. To keep things simple, this book will consider the two most popular: VB and C#. You can choose the language that feels more comfortable to you, or stick with your current favorite if you have one.

Visual Basic

The latest version of Visual Basic is the result of a dramatic overhaul of Microsoft's hugely popular Visual Basic language. With the inception of Rapid Application Development (RAD) in the 1990s, Visual Basic became extremely popular, allowing in-house teams and software development shops to bang out applications two-to-the-dozen. The latest version of VB has many advantages over older versions, most notably the fact that it has now became a fully object oriented language. At last, it can call itself a true programming language that's on a par with the likes of Java and C++. Despite the changes, VB generally stays close to the structured, legible syntax that has always made it so easy to read, use, and maintain.

C#

The official line is that Microsoft created C# in an attempt to produce a programming language that coupled the simplicity of Visual Basic with the power and flexibility of C++. However, there's little doubt that its development was at least hurried along by Microsoft's legal disputes with Sun. After Microsoft's treatment (some would say abuse) of Sun's Java programming language, Microsoft was forced to stop developing its own version of Java, and instead developed C# and another language, which it calls J#. We're not going to worry about J# here, as C# is preferable. It's easy to read, use, and maintain, because it does away with much of the confusing syntax for which C++ became infamous.

Summary

In this chapter, we started out by introducing key aspects of an ASP.NET page including directives, code declaration blocks, code render blocks, includes, comments, and controls. As the chapter progressed, we took a closer look at the two most popular languages that ASP.NET supports, and which we'll use throughout this book.

In the next chapter, we'll create a few more ASP.NET pages to demonstrate form processing techniques and programming basics, before we turn our attention to the topic of object oriented programming for the Web.


Excerpted from the book "Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition". Learn to create ASP.NET Web sites from scratch using freely available software. Copyright 2006 SitePoint Pty Ltd.


Build Your Own ASP.NET 2.0 Web Site Using C# & VB, 2nd Edition


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback

Internet.com
The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers