Article
ASP.NET 2.0: A Getting Started Guide
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.

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.