Home > Articles > Programming > Windows Programming

Building ASP.NET Pages

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Structure of an ASP.NET Page

You are now in a position to examine the formal structure of an ASP.NET page. The following is a list of the important elements of an ASP.NET page:

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

Each element is discussed in the following sections.


A directive controls how an ASP.NET page is compiled. The beginning of a directive is marked with the characters <%@ and the end of a directive is marked with the characters %>. A directive can appear anywhere within a page. By convention, however, a directive typically appears at the top of an ASP.NET page.

There are several types of directives that you can add to an ASP.NET page. Two of the most useful types are page and import directives.

Page Directives

You can use a page directive to specify the default programming language for a page. Page directives can also be used to enable tracing and debugging for a page.

To change the default programming language of an ASP.NET page from Visual Basic to C#, for example, you would use the following page directive:

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


The keyword Page in a page directive is optional. The following two directives are equivalent:

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

Another extremely useful page directive is the Trace directive. If you enable tracing for a page, additional information about the execution of the page is displayed along with the content of the page (see Figure 5). You can enable tracing for a page by including the following directive:

<%@ Page Trace="True" %>

After you enable tracing for a page, you can display trace messages by using two methods of the Trace class: Write() and Warn(). You can use either method to display a custom message in the trace information displayed at the bottom of the page. The only difference between the two methods is that the former method displays messages in black text, and the latter method displays messages in red text, which is easier to see.

Figure 5 Enabling page tracing.

The ASP.NET page in Listing 11 uses these methods to display various trace messages.

Listing 11—Trace.aspx

<%@ Page Trace="True" %>
<Script Runat="Server">

Sub Page_Load
 Dim strTraceMessage As String

 Trace.Warn( "Page_Load event executing!" )
 strTraceMessage = "Hello World!"
 Trace.Write( "The value of strTraceMessage is " & strTraceMessage )
End Sub



<h2>Testing Page Trace</h2>

<% Trace.Warn( "Rendering page content!" ) %>


To enable runtime error messages to be displayed on a page, you need to use the Debug directive. To display errors in your ASP.NET page, include the following directive:

<%@ Page Debug="True" %>

When you include this directive, if an error is encountered when processing the page, the error is displayed. In most cases, you also can view the source code for the exact statement that generated the error.

To enable both tracing and debugging for a page, combine the directives like this (the order of Debug and Trace is not important):

<%@ Page Debug="True" Trace="True" %>

Import Directives

By default, only certain namespaces are automatically imported into an ASP.NET page. If you want to refer to a class that isn't a member of one of the default namespaces, then you must explicitly import the namespace of the class or you must use the fully qualified name of the class.

For example, suppose that you want to send an email from an ASP.NET page by using the Send method of the SmtpMail class. The SmtpMail class is contained in the System.Web.Mail namespace. This is not one of the default namespaces imported into an ASP.NET page.

The easiest way to use the SmtpMail class is to add an Import directive to your ASP.NET page to import the necessary namespace. The page in Listing 12 illustrates how to import the System.Web.Mail namespace and send an email message.

Listing 12—ImportNamespace.aspx

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

<Script Runat="Server">

Sub Page_Load
 Dim mailMessage As SmtpMail

 mailMessage.Send( _
  "bob@somewhere.com", _
  "alice@somewhere.com", _
  "Sending Mail!", _
  "Hello!" )
End Sub



<h2>Email Sent!</h2>


The first line in Listing 12 contains an import directive. Without the import directive, the page would generate an error because it would not be able to resolve the SmtpMail class.

Instead of importing the System.Web.Mail namespace with the import directive, you could alternatively use its fully qualified name. In that case, you would declare an instance of the class like this:

Dim mailMessage As System.Web.Mail.SmtpMail

Code Declaration Blocks

A code declaration block contains all the application logic for your ASP.NET page and all the global variable declarations, subroutines, and functions. It must appear within a <Script Runat="Server"> tag.

Note that you can declare subroutines and functions only within a code declaration block. You receive an error if you attempt to define a function or subroutine in any other section of an ASP.NET page.

ASP Classic Note

In previous versions of ASP, you could declare a subroutine or function like this:

Sub mySub
  ... subroutine code
End Sub

Don't try this declaration with ASP.NET because it generates an error. You must use the <Script> tag with ASP.NET like this:

<Script runat="Server">
Sub mySub
 ...subroutine code
End Sub

The <Script Runat="Server"> tag accepts two optional attributes. First, you can specify the programming language to use within the <Script> tag by including a language attribute like this:

<Script Language="C#" Runat="Server">

If you don't specify a language, the language defaults to the one defined by the <%@ Page Language %> directive mentioned in the previous section. If no language is specified in a page, the language defaults to Visual Basic.

ASP Classic Note

In previous versions of Active Server Pages, you could include multiple languages in the same page by using the language attribute with the <Script> tag. This technique doesn't work with ASP.NET. You get an error if you attempt to use more than one language in the same page.

The second optional attribute of the <Script Runat="Server"> tag is SRC. You can use it to specify an external file that contains the contents of the code block. This is illustrated in Listings 13 and 14.

Listing 13—ExternalFile.aspx

<Script Runat="Server" SRC="ApplicationLogic.aspx"/>


<form Runat="Server">

<asp:label id="lblMessage" Runat="Server"/>

 Text="Click Here!"



Listing 14—ApplicationLogic.aspx

Sub Button_Click( s As Object, e As EventArgs )
 lblMessage.Text = "Hello World!"
End Sub

The page in Listing 13, ExternalFile.aspx, uses the SRC attribute to include the code in Listing 14, ApplicationLogic.aspx.

ASP.NET Controls

ASP.NET controls can be freely interspersed with the text and HTML content of a page. The only requirement is that the controls should appear within a <form Runat="Server"> tag. And, for certain tags such as <span Runat="Server"> and <ASP:Label Runat="Server"/>, this requirement can be ignored without any dire consequences.

One significant limitation of ASP.NET pages is that they can contain only one <form Runat="Server"> tag. This means that you cannot group ASP.NET into multiple forms on a page. If you try, you get an error.

Code Render Blocks

If you need to execute code within the HTML or text content of your ASP.NET page, you can do so within code render blocks. The two types of code render blocks are inline code and inline expressions. Inline code executes a statement or series of statements. This type of code begins with the characters <% and ends with the characters %>.

Inline expressions, on the other hand, display the value of a variable or method (this type of code is shorthand for Response.Write). Inline expressions begin with the characters <%= and end with the characters %>.

The ASP.NET page in Listing 15 illustrates how to use both inline code and inline expressions in an ASP.NET page.

Listing 15—CodeRender.aspx

<Script Runat="Server">
 Dim strSomeText As String

 Sub Page_Load
  strSomeText = "Hello!"
 End Sub


<form Runat="Server">

The value of strSomeText is: 


<% strSomeText = "Goodbye!" %>
The value of strSomeText is: 



Notice that you can use variables declared in the code declaration block within the code render block. However, the variable has to be declared with page scope. The variable could not, for example, be declared within the Page_Load subroutine.

Server-side Comments

You can add comments to your ASP.NET pages by using server-side comment blocks. The beginning of a server-side comment is marked with the characters <%-- and the end of the comment is marked with the characters --%>.

Server-side comments can be added to a page for the purposes of documentation. Note that you cannot see the contents of server-side comment tags, unlike normal HTML comment tags, by using the View Source command on your Web browser.

Server-side comments can also be useful when you're debugging an ASP.NET page. You can temporarily remove both ASP.NET controls and code render blocks from a page by surrounding these elements with server-side comments. The page in Listing 16 illustrates this use.

Listing 16—ServerComments.aspx

<Script Runat="Server">
 Dim strSomeText As String
 Sub Page_Load
  strSomeText = "Hello!"
 End Sub


<form Runat="Server">

This is inside the comments
<asp:Label Text="hello!" Runat="Server" />
<%= strSomeText %>

This is outside the comments



Server-side Include Directives

You can include a file in an ASP.NET page by using one of the two forms of the server-side include directive. If you want to include a file that is located in the same directory or in a subdirectory of the page including the file, you would use the following directive:

<!-- #INCLUDE file="includefile.aspx" -->

Alternatively, you can include a file by supplying the full virtual path. For example, if you have a subdirectory named myDirectory under the wwwroot directory, you can include a file from that directory like this:

<!-- #INCLUDE virtual="/myDirectory/includefile.aspx" -->

The include directive is executed before any of the code in a page. One implication is that you cannot use variables to specify the path to the file that you want to include. For example, the following directive would generate an error:

<!-- #INCLUDE file="<%=myVar%>" -->


Instead of working with include directives, consider working with user controls instead. User controls provide you with more flexibility. For example, you can create custom properties and methods with a user control.

Literal Text and HTML Tags

The final type of element that you can include in an ASP.NET page is HTML content. The static portion of your page is built with plain old HTML tags and text.

You might be surprised to discover that the HTML content in your ASP.NET page is compiled along with the rest of the elements. HTML content in a page is represented with the LiteralControl class. You can use the Text property of the LiteralControl class to manipulate the pure HTML portion of an ASP.NET page.

The HTML content contained in the page in Listing 17, for example, is reversed when it is displayed (see Figure 6). The Page_Load subroutine walks through all the controls in a page (including the LiteralControl) and reverses the value of the Text property of each control.

Listing 17—Literal.aspx

<Script Runat="Server">

 Sub Page_Load
  Dim litControl As LiteralControl

  For each litControl in Page.Controls
   litControl.Text = strReverse( litControl.Text )
 End Sub



<b>This text is reversed</b>


Figure 6 Reversing the contents of a page.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020