Build Your Own ASP.NET Website Using C# And VB.NET 2

Share this article

In Chapter 1, you learned what ASP.NET is, and what it can do – you even know how to create a simple ASP.NET page. Don’t worry if it seems a little bewildering right now, because, as this book progresses, you’ll learn how to use ASP.NET at more advanced levels. Note that you can download these chapters in PDF format if you’d rather print them out and read them offline.

So far, you’ve installed the necessary software to get going and have been introduced to some very simple form processing techniques. As the next few chapters unfold, we’ll introduce more advanced topics, including controls, programming techniques, and more. Before we can begin developing applications with ASP.NET, however, you’ll need to understand the inner workings of a typical ASP.NET page. This will help you identify the various parts of the ASP.NET page referenced by the many examples within the book. 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.NET and C#. As this section begins to unfold, we’ll explore the differences, similarities, and power that the two languages provide in terms of 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 with the .aspx file name extension that can be placed on an IIS server equipped with ASP.NET. When a browser requests an ASP.NET page, the ASP.NET runtime (as a component of the .NET Framework’s Common Language Runtime, or CLR) parses and compiles the target file into a .NET Framework class. The application logic now contained within the new class is used in conjunction with the presentational HTML elements of the ASP.NET page to display dynamic content to the user. Sounds simple, right?
An ASP.NET page consists of the following elements:

  • Directives
  • Code declaration blocks
  • Code render blocks
  • ASP.NET server controls
  • Server-side comments
  • Server-side include directives
  • Literal text and HTML tags

It’s important to remember that ASP.NET pages are just text files with an .aspx extension that are processed by the runtime to create standard HTML, based on their contents. Presentational elements within the page are contained within the <body> tag, while application logic or code can be placed inside <script> tags. Remember this pattern from the sample at the end of the previous chapter?

1327_1
Figure 2.1 illustrates the various parts of that page.

Figure 2.1. All the elements of an ASP.NET page are highlighted. Everything else is literal text and HTML tags.

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 you should become familiar with these elements, the purpose that each serves, 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 settings when navigating between pages, aid in debugging (error-fixing), and allow you to import classes to use within your page’s code. Directives start with the sequence <%@, followed by the directive name, plus any attributes and their corresponding values, then end with %>. Although there are many directives that you can use within your pages, the two most important are the Import and Page directives. We will discuss directives 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.1, you can see that a Page directive was used at the top of the page as shown:

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

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

Unlike ASP, in ASP.NET, directives can appear anywhere on a page, but are most commonly written as the very first lines.

Code Declaration Blocks

In Chapter 3, VB.NET 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 presentation code. If you’re not working with code-behind pages, however, code declaration blocks must be used to contain all the application logic of your ASP.NET page. This application logic defines variables, subroutines, functions, and more. In our page, we place the code inside <script> tags, like so:

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

Here, the tags enclose some VB.NET code, but it could just as easily be C# if our page language were set thus:

<script runat="server"> 
void mySub() {
 // Code here
}
</script>
Comments in VB.NET and C# Code

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

In VB.NET 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 (//) does the same. C# code also lets you span a comment over multiple lines by beginning it with /* and ending it with */.

Before .NET emerged, ASP also supported such script tags using a runat="server" attribute, although 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> tag of your ASP.NET page. The sample ASP.NET page shown in Figure 2.1, for instance, contained the following code declaration block:

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

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

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

The <script runat="server"> tag accepts two other attributes, as well. You can set the language used in the block with 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 may only contain code in a single language; for instance, it is not possible to mix VB.NET and C# in the same page.

The second attribute available is src, which lets you specify an external code file to use within your ASP.NET page:

<script runat="server" language="VB" src="mycodefile.vb"> 
<script runat="server" language="C#" src="mycodefile.cs">
Code Render Blocks

You can use code render blocks to define inline code or inline expressions that execute when a page is rendered, and you may recognize these blocks from traditional ASP. Code within a code render block is executed immediately as it is encountered, usually when the page is loaded or rendered for the first time, and every time the page is loaded subsequently. Code within a code declaration block, on the other hand, occurring within script tags, is only executed 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 within <% and %> characters.

Inline expression render blocks can be compared to Response.Write() in classic ASP. They start with <%= and end with %>, and are used to display values of the variables and methods on a page.

Looking back at Figure 2.1, you can see both types of code render blocks:

<% Dim Title As String = "Zak Ruvalcaba" %> 
<%= Title %>

This equates to the following C#:

<% String Title = "Zak Ruvalcaba"; %> 
<%= Title %>

The first line represents an inline code render block and must contain complete statements in the appropriate language. Here, we’re setting the value of the Title variable to the string Zak Ruvalcaba. The last line is an example of an inline expression render block used to write out the value of the Title variable, Zak Ruvalcaba, onto the page.

ASP.NET Server Controls

At the heart of ASP.NET pages lies the server controls, which represent dynamic elements that your users can interact with. There are four basic types of server control: ASP.NET controls, HTML controls, validation controls, and user controls.

All ASP.NET controls must reside within a <form runat="server"> tag in order to function correctly. The only two exceptions to this rule are the HtmlGenericControl and the Label Web control.

Server controls offer the following advantages to ASP.NET developers:

  • We can access HTML elements easily from within our code: we can change their characteristics, check their values, or even dynamically update them straight from our server-side programming language of choice.
  • ASP.NET controls retain their properties even after the page has been processed. This process is known as view state. We’ll be covering view state later in this chapter. For now, just know that view state prevents the user from losing data that has already been entered into a form once it’s been sent to the server for processing. When the response comes back to the client’s browser, text box values, drop-down list selections, etc., are all retained through view state.
  • With ASP.NET controls, developers are able to separate the presentational elements (everything the user sees) and application logic (dynamic portions of the ASP.NET page) of a page so that each can be considered separately.

Because ASP.NET is all about controls, we’ll be discussing them in greater detail as we move through this book. For instance, in the next few chapters, we’ll discuss HTML controls and Web controls (Chapter 4, Web Forms and Web Controls), Validation controls (Chapter 5, Validation Controls), Data controls (Chapter 9, The DataGrid and DataList Controls), and so on.

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; anything found within these will not be displayed to the user by the browser. ASP.NET comments look very similar, but use the sequences <%-- and --%>.

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

<%-- 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. Don’t use HTML comments to try and comment out ASP.NET code. Consider the following example:

<!-- 
<button runat="server" id="myButton" onServerClick="Click">Click  
Me</button>
<% Title = "New Title" %>
-->

Here, it looks as if a developer has attempted to use an HTML comment to hide not only an HTML button control, but a code render block as well. Unfortunately, HTML comments will only hide things 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, in fact, have been processed by ASP.NET, and the value of the variable Title will be changed to New Title. The code could be modified to use server-side comments very simply:

<%--  
<button runat="server" id="myButton" onServerClick="Click">Click  
Me</button>
<% Title = "New Title" %>
--%>


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

Server-Side Include Directives

Server-side include directives enable developers to insert the contents of an external file anywhere within an ASP.NET page. In the past, developers used server-side includes when inserting connection strings, constants, and other code that was generally repeated throughout the entire site.

There are two ways your server-side includes can indicate the external file to include: using either the file or the virtual attribute. If we use file, we specify its filename as the physical path on the server, either as an absolute path starting from a drive letter, or as a path relative to the current file. Below, we see a file server-side include with a relative path:

<!-- #INCLUDE file="myinclude.aspx" -->
virtual server-side includes, on the other hand, specify the file's location on the Website, either with an absolute path from the root of the site, or with a path relative to the current page. The example below uses an absolute virtual path:

<!-- #INCLUDE virtual="/directory1/myinclude.aspx" -->

Note that although server-side includes are still supported by ASP.NET, they have been replaced by a more robust and flexible model known as user controls. Discussed in Chapter 16, Rich Controls and User Controls, user controls allow for developers to create a separate page or module that can be inserted into any page within an ASP.NET application.

Literal Text and HTML Tags

The final element of an ASP.NET page is plain old text and HTML . Generally, you cannot do without these elements, and HTML is the means for displaying the information from your ASP.NET controls and code in a way that’s suitable for the user. Returning to the example in Figure 2.1 one more time, let’s focus on the literal text and HTML tags:

<%@ Page Language="VB" %>  
<html>  
<head>  
<title>Sample Page</title>  
 
<script runat="server">  
Sub ShowMessage(s As Object, e As EventArgs)  
 lblMessage.Text = "Hello World"  
End Sub  
</script>  
 
</head>  
<body>  
 
<form runat="server">  
<%-- Declare the title as string and set it --%>  
<asp:Label id="lblMessage" runat="server" />  
<% Dim Title As String = "Zak Ruvalcaba's Book List" %>  
<%= Title %>  
</form>  
 
</body>  
</html>

As you can see in the bold code, literal text and HTML tags provide the structure for presenting our dynamic data. Without them, there would be no format to the page, and the browser would be unable to understand it.

Now you should understand what the structure of an ASP.NET page looks like. 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 these elements. For the most part, all of your development will be modularized within code declaration blocks. 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 outline the various languages used within ASP.NET, talk a little about view state, and look at working with directives in more detail.

View State

As I mentioned briefly in the previous section, ASP.NET controls automatically retain their data when a page is sent to the server by a user clicking a submit button. Microsoft calls this persistence of data view state. In the past, developers would have to hack a way to remember the item selected in a drop-down menu or keep the contents of a text box, typically using a hidden form field. This is no longer the case; ASP.NET pages, once submitted to the server for processing, automatically retain all information contained within text boxes, items selected within drop-down menus, radio buttons, and check boxes. Even better, they keep dynamically generated tags, controls, and text. Consider the following ASP page, called sample.asp:

<html>  
<head>  
 <title>Sample Page using VBScript</title>  
</head>  
<body>  
<form method="post" action="sample.asp">  
 <input type="text" name="txtName"/>  
 <input type="Submit" name="btnSubmit" text="Click Me"/>  
<%  
If Request.Form("txtName") <> "" Then  
 Response.Write(Request.Form("txtName"))  
End If  
%>  
 
</form>  
</body>  
</html>

If you save this example in the WebDocs subdirectory of wwwroot that you created in Chapter 1, Introduction to .NET and ASP.NET, you can open it in your browser by typing http://localhost/WebDocs/sample.asp, to see that view state is not automatically preserved. When the user submits the form, the information that was previously typed into the text box is cleared, although it is still available in Request.Form("txtName"). The equivalent page in ASP.NET, ViewState.aspx, demonstrates data persistence using view state:

Example 2.1. ViewState.aspx

<html>  
<head>  
<title>Sample Page using VB.NET</title>  
<script runat="server" language="VB">  
Sub Click(s As Object, e As EventArgs)  
 lblMessage.Text = txtName.Text  
End Sub  
</script>  
</head>  
 
<body>  
<form runat="server">  
 <asp:TextBox id="txtName" runat="server" />  
 <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click"  
     runat="server" />  
 <asp:Label id="lblMessage" runat="server" />  
</form>  
</body>  
</html>

Example 2.2. ViewState.aspx

<html>  
<head>  
<title>Sample Page using C#</title>  
<script runat="server" language="C#">  
void Click(Object s, EventArgs e) {  
 lblMessage.Text = txtName.Text;  
}  
</script>  
</head>  
 
<body>  
<form runat="server">  
 <asp:TextBox id="txtName" runat="server" />  
 <asp:Button id="btnSubmit" Text="Click Me" OnClick="Click"  
     runat="server" />  
 <asp:Label id="lblMessage" 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.2, 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 because of view state:

1327_2
Figure 2.2. ASP.NET supports view state. When a page is submitted, the information within the controls is preserved.

You can see the benefits of view state already. But where is 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" value="dDwtMTcyOTAyO  
DAwNzt0PDtsPGk8Mj47PjtsPHQ8O2w8aTwzPjs+O2w8dDxwPGw8aW5uZXJodG  
1sOz47bDxIZWxsbyBXb3JsZDs+Pjs7Pjs+Pjs+Pjs+d2wl7GlhgweO9LlUihS  
FaGxk6t4=" />

This is a standard HTML hidden form field with the value set to the encrypted data from the form element. As soon as you submit the form for processing, all information relevant to the view state of the page is stored within this hidden form field.

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" %>

Speaking of directives, it’s time we took 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 an extension like .aspx on an HTML file will make the .NET Framework process the page. However, before you can work with certain, more advanced features, you will need to know how to use directives.

We’ve already talked a little about directives and what they can do earlier in this chapter. You learned that directives control how a page is created, specify settings when navigating between pages, aid in finding errors, and allow you to import advanced functionality to use within your code. Three of the most commonly used directives are:

Page

Defines page-specific attributes for the ASP.NET page, such as the language used.

Import

Makes functionality defined elsewhere available in a page through the use of namespaces. You will become very familiar with this directive as you progress through this book.

Register

As you will see in Chapter 16, Rich Controls and User Controls, you would use this directive to link a user control to the ASP.NET page.

You will become very familiar with these three directives, as they’re the ones that we’ll be using the most in this book. You’ve already seen the Page directive in use. The Import directive imports extra functionality for use within your application logic. The following example, for instance, imports the Mail class, which you could use to send email from a page:

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

The Register directive allows you to register a user control for use on your page. We’ll cover these in Chapter 16, Rich Controls and User Controls, 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 currently supports many different languages and there is no limit to the number of languages that could be made available. If you’re used to writing ASP, you may think the choice of VBScript would be obvious. With ASP.NET however, Microsoft has done away with VBScript and replaced it with a more robust and feature-rich alternative: VB.NET.

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 are used throughout the remainder of the book. 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 the choice of development language 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 language in and of itself. .NET’s support for many different languages lets developers choose based on what they’re familiar with, and start from there. To keep things simple, in this book we’ll consider the two most popular, VB.NET and C#, giving you a chance to choose which feels more comfortable to you, or stick with your current favorite if you have one.

VB.NET

Visual Basic.NET or VB.NET 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 nineties, Visual Basic became extremely popular, allowing inhouse teams and software development shops to bang out applications two-to-the-dozen. VB.NET has many new features over older versions of VB, most notably that it has now become a fully object-oriented language. At last, it can call itself a true programming language on a par with the likes of Java and C++. Despite the changes, VB.NET 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. Following legal disputes with Sun about Microsoft’s treatment (some would say abuse) of Java, 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, you were introduced to the two most popular languages that ASP.NET supports, which we’ll use throughout the book.

In the next chapter, we’ll create more ASP.NET pages to demonstrate some form processing techniques and programming basics, before we finally dive in and look at object oriented programming for the Web.

Look out for more chapters from Build Your Own ASP.NET Website Using C# And VB.NET in coming weeks. If you can’t wait, download all the sample chapters, or order your very own copy now!

Frequently Asked Questions (FAQs) about ASP.NET Basics

What is the difference between ASP.NET and ASP.NET Core?

ASP.NET is a framework for building web applications developed by Microsoft. It is part of the .NET platform and allows developers to build dynamic websites, web applications, and web services. On the other hand, ASP.NET Core is a redesign of ASP.NET, with architectural changes that result in a leaner, more modular framework. It’s a cross-platform framework that can run on Windows, Linux, and macOS, unlike ASP.NET which is Windows-only.

How can I create a block comment in ASP.NET?

In ASP.NET, you can create a block comment by using /* and */. Any text between these symbols will be treated as a comment and will not be executed as code. For example:
/*
This is a block comment.
It can span multiple lines.
*/

What are the main features of ASP.NET?

ASP.NET comes with a variety of features that make it a powerful tool for web development. These include server controls, data binding, state management, caching services, and security. It also supports multiple languages, including C# and VB.NET, and allows for the separation of code and content through its code-behind model.

How can I start developing with ASP.NET?

To start developing with ASP.NET, you’ll need to install the .NET SDK (Software Development Kit) and an IDE (Integrated Development Environment) like Visual Studio. Once you have these installed, you can create a new ASP.NET project and start writing your code.

What is the role of the Global.asax file in ASP.NET?

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules. These events include application start, application end, session start, and session end.

How can I handle errors in ASP.NET?

ASP.NET provides several ways to handle errors. You can use try-catch blocks to handle exceptions at the method level, or you can use the Page_Error or Application_Error methods to handle exceptions at the page or application level. You can also use custom error pages to provide a user-friendly response to errors.

What is the difference between Web Forms and MVC in ASP.NET?

Web Forms and MVC are two different programming models in ASP.NET. Web Forms is an event-driven model that uses server controls and view state, making it easy to develop applications quickly. MVC, on the other hand, is a model-view-controller model that separates an application into three interconnected parts. This separation allows for more control over the HTML, better testability, and cleaner code.

How can I secure my ASP.NET application?

ASP.NET provides several features to help secure your application. These include authentication, authorization, and secure communication. You can use forms authentication to authenticate users, role-based authorization to control access to resources, and SSL to secure communication between the client and the server.

What is the life cycle of an ASP.NET page?

The life cycle of an ASP.NET page starts with the request being sent by the client to the server. The server processes the request, executes the appropriate event handler code, and sends the response back to the client. The life cycle includes stages like initialization, loading, rendering, and unloading.

How can I optimize the performance of my ASP.NET application?

There are several ways to optimize the performance of your ASP.NET application. These include using caching to reduce the load on the server, using view state sparingly to reduce page size, and using paging to limit the amount of data sent to the client. You can also use the ASP.NET tracing feature to monitor the performance of your application and identify potential bottlenecks.

Zak RuvalcabaZak Ruvalcaba
View Author

Involved in the Web since 1995, Zak is founder of and advisor to Module Media, a full service design and development firm in San Diego. He is author of �The Ten Minute Guide to Dreamweaver 4� and �Dreamweaver MX Unleashed�, and SitePoint's own Build Your Own ASP.NET Website Using C# and VB.NET.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week