Microsoft ASP.NET Step by Step

( 5 )

Overview

There is no book that we are aware of, either current, or in the pipeline, which matches this book. There are books already available that touch on ASP.NET performance topics, such as Microsoft ASP.NET Step-by-Step Guide. However, the difference with our book is that (1) it is focused exclusively on ASP.NET performance and optimization and (2) it will go much further in depth than any book currently on the market. The current ASP.NET books all focus on how-to, with performance issues tossed in for good measure. ...

See more details below
Available through our Marketplace sellers.
Other sellers (Paperback)
  • All (23) from $1.99   
  • New (2) from $27.52   
  • Used (21) from $1.99   
Close
Sort by
Page 1 of 1
Showing All
Note: Marketplace items are not eligible for any BN.com coupons and promotions
$27.52
Seller since 2008

Feedback rating:

(173)

Condition:

New — never opened or used in original packaging.

Like New — packaging may have been opened. A "Like New" item is suitable to give as a gift.

Very Good — may have minor signs of wear on packaging but item works perfectly and has no damage.

Good — item is in good condition but packaging may have signs of shelf wear/aging or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Acceptable — item is in working order but may show signs of wear such as scratches or torn packaging. All specific defects should be noted in the Comments section associated with each item.

Used — An item that has been opened and may show signs of wear. All specific defects should be noted in the Comments section associated with each item.

Refurbished — A used item that has been renewed or updated and verified to be in proper working condition. Not necessarily completed by the original manufacturer.

New
0735612870 BRAND NEW NEVER USED IN STOCK 125,000+ HAPPY CUSTOMERS SHIP EVERY DAY WITH FREE TRACKING NUMBER

Ships from: fallbrook, CA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
$45.00
Seller since 2015

Feedback rating:

(214)

Condition: New
Brand new.

Ships from: acton, MA

Usually ships in 1-2 business days

  • Standard, 48 States
  • Standard (AK, HI)
Page 1 of 1
Showing All
Close
Sort by
Sending request ...

Overview

There is no book that we are aware of, either current, or in the pipeline, which matches this book. There are books already available that touch on ASP.NET performance topics, such as Microsoft ASP.NET Step-by-Step Guide. However, the difference with our book is that (1) it is focused exclusively on ASP.NET performance and optimization and (2) it will go much further in depth than any book currently on the market. The current ASP.NET books all focus on how-to, with performance issues tossed in for good measure. Performance Tuning and Optimization for ASP.NET Applications tackles performance issues head on, and makes them the central topic.

Read More Show Less

Product Details

  • ISBN-13: 9780735612877
  • Publisher: Microsoft Press
  • Publication date: 1/23/2002
  • Edition description: BK&CD-ROM
  • Pages: 519
  • Product dimensions: 7.28 (w) x 9.32 (h) x 1.40 (d)

Meet the Author

G. Andrew Duthie is an experienced ASP.NET developer. He is a frequent speaker at ASP.NET conferences, and is the author of a number of books on ASP.NET and Visual Interdev.

Read More Show Less

Table of Contents

Acknowledgments
Finding Your Best Starting Point
Installing the Sample Files
Conventions Used in this Book
Pt. I Getting Started with ASP.NET 1
Ch. 1 ASP.NET Overview 3
Ch. 2 Using ASP.NET Development Tools 17
Pt. II ASP.NET Web Development Fundamentals 29
Ch. 3 ASP.NET Development Overview 31
Ch. 4 Understanding Programming Basics 51
Pt. III ASP.NET Web Applications 79
Ch. 5 Creating an ASP.NET Web Application 81
Ch. 6 Managing Application State 97
Ch. 7 Configuring an ASP.NET Application 117
Ch. 8 Security in ASP.NET 167
Pt. IV ASP.NET Web Forms 207
Ch. 9 Creating Web Forms 209
Ch. 10 Using Server Controls 251
Ch. 11 Accessing and Binding Data 297
Ch. 12 Creating Custom Server Controls 351
Pt. V ASP.NET Web Services 395
Ch. 13 Creating and Using Web Services 397
Ch. 14 Using Caching to Improve Performance 427
Ch. 15 Deploying an ASP.NET Application 445
Ch. 16 Tracing and Debugging ASP.NET Applications 461
App. A Migrating from ASP to ASP.NET 477
App. B: Additional Code Listings 489
Afterword 497
Index 499
About the Author 521
Read More Show Less

First Chapter

  • Anatomy of an ASP.NET Web Form
  • Understanding Page Elements
  • Understanding Page Lifetime
  • Using Directives
  • @ Page Examples
  • @ Control
  • The Page Class
  • Writing Code in Web Forms
  • Creating and Using User Controls
  • Using Server Controls
  • Event Handling
  • Handling Page Events
  • Handling Control Events
  • Handling Page Errors
  • Page Runtime Structure
  • Using Code-Behind in Web Forms
  • Separating Code from UI

9   Creating Web Forms

In this chapter, you will learn about

  • Creating Web Forms pages
  • How the various parts of a Web Form work together to produce their magic
  • Automatic handling of postbacks
  • Using code-behind classes to separate executable code from HTML markup and server control tags

"Let's start from the very beginning, a very good place to start. When you read you begin with A… B… C… when you…"

No, that won't do at all. But you don't have to channel Julie Andrews in The Sound of Music to figure out Web Forms. And you will start at the beginning… the beginning of the page, that is.

Anatomy of an ASP.NET Web Form

In previous chapters, you saw some examples of very simple ASP.NET pages, and you've seen some more complicated examples as well. The simplest ASP.NET page consists of plain HTML and is named with the .aspx extension. While that's perfectly valid, it's also missing a lot of what makes ASP.NET pages and what makes them Web Forms.

Web Forms go beyond what classic ASP pages offered, adding new directives, new reusability options in the form of user controls and server controls, and a new server-side data-binding syntax, to name a few. This section will explore how a page is put together and how you can use these new features in your Web Forms.

The following listing shows an example of a relatively simple Web Forms page.

HelloSimple.aspx

<%-- Example of the @ Page directive --%>
<%@ Page Language="vb" ClassName="Hello" %>
<html>
<head>
<script runat="server">
‘this is a script code declaration block
Private _name As String = "Andrew"
      Public Property Name As String
Get
Return _name
End Get
Set
_name = Value
End Set
End Property
      Sub SayHello()
Label1.Text = "Hello, " & _name & "!"
End Sub
      Sub Page_Load(Sender As Object, E As EventArgs)
If IsPostBack Then
If NameTextBox.Text <> "" Then
Name = NameTextBox.Text
End If
SayHello
End If
End Sub
   </script>
</head>
<body>
<!-- this is a server side form -->
<form runat="server">
<!-- a Server Control -->
<asp:Label id="NameLabel" runat="server">Name: </asp:Label>
<!-- a Server Control -->
<asp:textbox id="NameTextBox" runat="server"/>
<!-- a Server Control -->
<asp:button id="NameButton" text="Submit" runat="server"/>
</form>
<!-- a Server Control -->
<asp:Label id=Label1 runat="server"/>
</body>
</html>

This example contains a directive, HTML markup, a <script> code declaration block, a server-side form, and several server controls. The following sections describe all of these elements, as well as other elements that may be used in a Web Form page.

Understanding Page Elements

HelloSimple.aspx (the preceding listing) shows examples of many of the elements that may be used in an ASP.NET Web Form. The elements used in HelloSimple.aspx include server-side comments, the @ Page directive, static HTML, a server-side <script> code-declaration block containing both event handlers and methods, and several ASP.NET server controls. The following table describes the elements that may be used in an ASP.NET page.

ASP.NET Page Elements 

Element Description
Static HTML tags These standard HTML elements are treated by ASP.NET as literal controls, and are rendered to the client browser as represented in the source file.
HTML comments Syntax: <!-- -->. HTML comments allow descriptive text to be added to a page. This text is sent to the client but is not rendered by the browser.
Directives Directives, such as the @ Page directive, provide the ASP.NET runtime with information about how to process the page. Using directives, you can control such ASP.NET features as session state, wiring up of events, and output caching, as well as importing namespaces and registering custom controls for use within a page.
Server-side code Code can be contained in either server-side <script> code declaration blocks or <% %> render blocks. See "Writing Code in Web Forms" on page 228 for information on using code declaration and render blocks. ASP.NET supports server-side code in any language that targets the runtime.
Event handlers Event handlers are procedures in <script> code declaration blocks that handle page or server control events, such as Page_Load or control Click events. Most ASP.NET code should be written in or called from event handlers, rather than being written in render blocks.
<script> code declaration blocks These blocks are used to contain page-level procedures and to declare variables that are global to the page. Executable code, other than global variable declarations in code declaration blocks, must be contained within a procedure declaration. Server-side code declaration blocks must have the runat="server" attribute, as shown in HelloSimple.aspx.
<% %> render blocks These blocks are used to contain executable code not contained within procedures. Overuse of render blocks can result in code that is difficult to read and maintain.
Client-side <script> blocks These blocks are used to contain script code to be executed on the client, usually in response to a client-side event. Choice of language (set by the language attribute) is dictated by the languages supported by the target browser. JavaScript is the most common choice for cross-browser compatibility in client scripts.
Server-side comments Syntax: <%-- --%>. Server-side comments allow descriptive text to be added to a page. Unlike HTML comments, this text is not sent to the client.
User controls These are custom controls that are defined declaratively in files with the .ascx extension. They provide a simple and straightforward mechanism for reuse of UI and UI-related code, and can contain most of the same elements as Web Forms pages.
ASP.NET server controls This set of built-in controls provides ASP.NET developers with a programming model that mimics that of Visual Basic. Controls are added to a page, and programmers write code to handle events raised by users' interaction with the controls at runtime. ASP.NET provides two sets of built-in controls: the HTML controls, which provide a 1-to-1 mapping of server-side controls for most HTML elements; and the Web controls, which provide a set of controls that are very similar to the Visual Basic UI controls.
Custom server controls Custom server controls are another mechanism for reuse in ASP.NET. They're defined in class files (.cs or .vb files) and are precompiled into managed assemblies before use.

Understanding Page Lifetime

The goal of the ASP.NET Web Forms programming model is to provide an experience similar to that of a Visual Basic rich client event-driven application, in which user actions, such as selecting an item from a list or clicking a button, cause server-side code to be executed. This is accomplished through postbacks.

The first time that an ASP.NET Web Forms page is executed, the code contained within the page (and any code-behind class associated with the page) is compiled into a class that inherits from the Page base class. The following figure shows the relationship between the page, its code-behind class (if any), and the compiled assembly. Once compiled, the class is executed, the resulting HTML is rendered to the browser, and the class is removed from memory.

(Image Unavailable)

Each ASP.NET Web Forms page contains a server-side <form> tag that directs the page to post back to itself when the form is submitted by the user. Many ASP.NET server controls also render JavaScript to the client, allowing actions such as selecting an item in a drop-down list to cause a postback. The ASP.NET runtime also renders a hidden form field to the page that allows the page to maintain its state between requests.

The postback and hidden field are key, because when the client is interacting with the page, there is no code running on the server at all. The postback and hidden field allow the page to be reconstituted on the server. Also, they allow code to be executed in response to the event raised by the user action, and based on any changes to the form fields. Once the page has been processed and the output rendered to the browser, the page and its controls are again discarded. The steps in this process are as follows:

  1. The user requests the page from the browser.
  2. The page and controls are loaded and initialized.
  3. If the page request is the result of a postback, the control state is loaded from the viewstate (hidden form field), and any changes submitted by the user are applied. (Note that both the original values in the viewstate and the updated values are available to server-side code.)
  4. Page event handlers and event handlers for events triggered by user actions are executed.
  5. Control state is saved to viewstate (hidden form field).
  6. HTML output from the page is rendered to the browser.
  7. The page and controls are unloaded.

It's important to note that while most server controls save their state to viewstate automatically, the same is not true for properties that you define in your pages, or in user controls or custom server controls. You'll learn how to use viewstate for storing custom control state in Chapter 12.

Using Directives

If you've developed a classic ASP page, you've worked with directives. There were few directives in classic ASP, but they were important. Most prominent were the @ Language directive and the #Include directive. The @ Language directive, which appeared at the top of every classic ASP page, told the ASP runtime which language engine to use in interpreting script found in <% %> render blocks in the page. The #Include directive told the ASP interpreter to include a particular file inline with the current ASP page.

Directives are simply ways for developers to declaratively determine how certain aspects of a program will operate. In classic ASP, this was somewhat limited. In fact, there were only the following four directives in classic ASP, in addition to the @ Language directive:

  • @ Codepage Used in globalization to set the code page for an ASP page
  • @ EnableSessionState Used to disable session state for a page
  • @ LCID Used to set the locale identifier for a page
  • @ Transaction Used to specify whether and how the page participates in COM+ transactions

ASP.NET greatly expands the use of directives, adding a number of useful directives for everything from controlling page behavior and configuration to caching page output. In addition, directives in ASP.NET have attributes, which increase their power and flexibility. The classic ASP directives listed previously are represented in ASP.NET as attributes of the @ Page directive, which is described in the next section.

@ Page

The @ Page directive, which is allowed in .aspx files only, defines page-specific attributes that are used by ASP.NET language compilers and the runtime to determine how the page will behave. The default values for a few of these attributes are set in the Pages configuration section in Machine.config. Some of the attributes, including AutoEventWireup, are set or overridden in pages created by Visual Studio .NET. The attributes available for the @ Page directive are listed in the following table.

@ Page Attributes 

Attribute Values Purpose
AspCompat true/false Provides compatibility with COM components created with Visual Basic 6.0 (or earlier) by forcing the page to be run in an STA (Single Threaded Apartment). Also provides the component with access to unmanaged instances of the ASP intrinsics (Session, Application, Request, etc.). This setting will likely degrade performance, so use it only when necessary. Default is false.
AutoEventWireup true/false
Default is set in the <pages> section of Machine.config or Web.config.
Determines whether or not handlers for events such as Page_Load are set up automatically. See "Event Handling" on page 240 for more information. Default is true.
Buffer true/false
Default is set in the <pages> section of Machine.config or Web.config.
Determines whether rendered output is buffered before being sent to the client or is sent as it is rendered. Default is true.
ClassName Any valid class name. Determines the name of the page generated by dynamically compiling the page. This attribute works with or without Codebehind, and with either the Src or Codebehind attributes. The default behavior if this attribute is omitted is for the page name to be in the form filename_aspx.
ClientTarget Any valid UserAgent string. Available values are set in the <clientTarget> section of Machine.config or Web.config. Determines the target browser for which server controls should render output. The User Agent string should be one recognized by the server controls being used.
Codebehind File name of code–behind class. This attribute is used in Visual Studio .NET to locate code-behind classes to be compiled during a build operation. It is not used by the ASP.NET runtime.
CodePage Any valid code page value. Same as in classic ASP.
CompilerOptions String containing valid compiler options. Allows developers to pass compiler options for the page to the compiler. For Visual Basic .NET and C#, this can be any valid sequence of command-line switches for the compiler.
ContentType Any valid MIME type (such as "text/html" or "application/ vnd.ms-excel"). Sets the MIME type for the page output. This attribute is useful when returning binary content (such as images) to the client.
Culture Any valid culture string (such as en-US for US English). Determines the culture setting for the page.
Debug true/false
Default is set by the debug attribute of the <compilation> section of Machine.config or Web.config.
Determines whether pages are compiled with debug symbols or without. This setting affects performance, so production applications should have this set to false. The default is false.
Description Any string. Provides a text description of the page. This attribute is ignored by the ASP.NET runtime.
EnableSessionState true/false/readonly
Default is set in the <pages> section of Machine.config or Web.config.
Determines whether a request to the page will initiate a new session, and whether or not the page can access or modify data stored in an existing session. Default is true.
EnableViewState true/false
Default is set in the <pages> section of Machine.config or Web.config.
Determines whether or not viewstate is enabled for the page. ViewState allows server controls to save their current state from request to request. Default is true.
EnableViewStateMac true/false
Default is set in the <pages> section of Machine.config or Web.config.
Determines whether ASP.NET runs a Machine Authentication Check (MAC) on the content of the hidden form field that is used to store viewstate, to ensure that it has not been altered on the client. Default is false.
ErrorPage Any valid URL. Specifies a page to which the client is redirected if there is an unhandled exception in the page.
Explicit true/false
Default is set in the <compilation> section of Machine.config or Web.config.
Determines whether code written in Visual Basic is subject to the Option Explicit rule when compiled. Default is true.
Inherits Any class derived from the Page class. Format is "namespacename.classname" or "classname". Specifies a code-behind class for the page. Any code contained in the page is combined with the code in the code-behind class into a single class.
Language Any valid string for an installed .NET language (such as "vb"/ "visualbasic", "c#"/ "cs"/"csharp", etc.) Default is set in the <compilation> section of Machine.config or Web.config. Specifies the language compiler to be used to compile the page. Default is vb.
LCID Any valid locale identifier. Same as classic ASP.
ResponseEncoding Any valid encoding string. Default is set in the <globalization> section of Machine.config or Web.config. Used in globalization to set the character encoding for the HTTP response. Default is utf-8.
Src File name of code- behind class Specifies the name of a code-behind class file to be compiled dynamically at runtime.
Strict true/false Determines whether code written in Visual Basic is subject to the Option Strict rule when compiled. Default is false.
Trace true/false
Default is set in the <trace> section of Machine.config or Web.config.
Determines whether the page includes trace output. Default is false.
TraceMode SortByTime/SortByCategory
Default is set in the <trace> section of Machine.config or Web.config.
Determines how the trace output is sorted when tracing is enabled. Default is SortByTime.
Transaction One of the following:
NotSupported
Supported
Required
RequiresNew
Determines whether and how the page will participate in COM+ transactions. Default is NotSupported.
WarningLevel 0 – 4 Specifies the warning level at which the compiler should abort page compilation. Lower numbers allow compilation to continue through warnings of greater severity. Levels 2–4 apply to C# only.

@ Page Examples

In this section, we'll take a look at a couple of examples of using the @ Page directive. The first example will show how to enable debugging of ASP.NET pages, and the second will show how to enable page-level tracing.

Enabling Debug Information

By default, ASP.NET pages are compiled without debug symbols. This is good for performance, but one of the major advances that ASP.NET offers is much richer error information than was available in classic ASP. However, this functionality requires debug symbols to be included when your page is compiled, so you may wish to turn this option on while you are developing. (Just remember to turn it back off before you deploy your application, for better performance.) Here's how to enable the insertion of debug symbols on a page-by-page basis:

  1. Open the desired page in a text editor, or in Visual Studio .NET.
  2. Add the debug attribute to the @ Page directive, with a value of true.

    <%@ Page debug="true" %>

  3. Save and close the file. Now if you encounter an unhandled error in the page, ASP.NET will provide you with debug information, including the source file in which the error occurred, the error message, and the line of the error, as shown in the following figure.
  4. (Image Unavailable)

Enabling Tracing

By default, the trace functionality is not enabled for ASP.NET pages. As with the default setting for the debug attribute, this is good for performance, since there is overhead associated with tracing. Tracing enables you to view information about the current request, including the collections (cookies, forms, headers, querystrings, and server variables) associated with the request. Here's how to enable tracing on a page-by-page basis:

  1. Open the desired page in a text editor, or in Visual Studio .NET.
  2. Add the trace attribute to the @ Page directive, with a value of true. <%@ Page trace="true" %>
  3. Save and close the file. When you request the file from a browser, you'll be able to see the trace information appended to the page output, as shown in the following figure.
  4. (Image Unavailable)

For more information on tracing and its uses in debugging ASP.NET applications, refer to Chapter 16.

@ Control

The @ Control directive, which is allowed in .ascx files only, performs the same function as the @ Page directive. However, instead of setting attributes for pages, it sets the attributes for user controls, which are reusable snippets of code named with the .ascx file extension. The attributes exposed by the @ Control directive are a subset of those exposed by the @ Page directive, and their purpose and values are the same as in the @ Page Attributes table beginning on page 215. The attributes available for the @ Control directive are as follows:

  • AutoEventWireup
  • ClassName
  • Codebehind
  • CompilerOptions
  • Debug
  • Description
  • EnableViewState
  • Explicit
  • Inherits
  • Language
  • Strict
  • Src
  • WarningLevel

@ Import

The @ Import directive is used to import either a .NET Framework namespace or a custom namespace into a page. Importing a namespace allows you to write code against the members of that namespace without explicitly specifying the namespace each time. The @ Import directive has only one attribute, Namespace, which specifies the namespace to import. Each @ Import directive can have only one Namespace attribute, so you must use a separate @ Import directive for each namespace you wish to import. For example, to use the .NET Framework SmtpMail and MailMessage classes to send e-mail from an ASP.NET page, you would need to add the System.Web.Mail namespace to your page, as follows:

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

Then, to create an instance of the MailMessage class, you would use the following:

Dim myMail As New MailMessage

Without the @ Import directive, you would need to use the following:

Dim myMail As New System.Web.Mail.MailMessage

@ Implements

The @ Implements directive is used to implement a defined interface from within an ASP.NET page. An interface provides an abstract definition of a set of methods and properties. When you implement an interface, you commit to supporting the methods and properties defined by the interface, and you must create matching method and property definitions in your .aspx file, using <script> blocks. The @ Implements directive can't be used to implement interfaces in a code-behind file. It has one attribute, interface, which specifies the interface being implemented.

@ Register

The @ Register directive is used with both user controls and custom server controls to register them for use within a page. The @ Register directive's attributes are listed in the following table.

@ Register Attributes

Attribute Value Purpose
Assembly Any valid assembly name. The assembly name should not contain a file extension. Specifies the precompiled assembly for a custom server control. Used with the Namespace and TagPrefix attributes. The assembly named needs to be available to the application, either by being placed in the bin subdirectory of the application or by being installed into the global assembly cache.
Namespace Any valid namespace name. Specifies the namespace to be associated with the tag prefix specified by the TagPrefix attribute.
Src Any valid path to a user control (.ascx) file Accepts either relative or absolute URLs. Specifies the location of a user control associated with a TagName/TagPrefix pair.
TagName Any string (must be valid for XML). Specifies an alias for a user control to be used in implementing the user control within the page. Must be used with the TagPrefix attribute.
TagPrefix Any string (must be valid for XML). Specifies an alias for a tag prefix for a user control or custom server control to be used in implementing the control within the page. If used without the TagName attribute, as with a custom server control, the tag name is the same as the class name defined in the server control assembly specified by the Assembly and Namespace attributes.

For examples of the use of the @ Register directive, please see "Creating and Using User Controls" on page 231 and "Using Server Controls" on page 236.

@ Assembly

The @ Assembly directive is used to link an assembly into a page at compilation time. This allows developers to use all of the classes, methods, and so forth exposed by the assembly as if they were part of the page. The @ Assembly directive's attributes are listed in the following table. Only one of the Name and Src attributes of the @ Assembly directive may be used at a time.

@ Assembly Attributes

Attribute Value Purpose
Name Any valid assembly name. Specifies the name of a compiled assembly to be linked to when the page is compiled.
Src Any valid path to a class source file (.vb, .cs, etc.). Specifies the path to a source file to be dynamically compiled and linked to the current page.

Note that it is not necessary to use the @ Assembly directive to link in assemblies residing in the bin subdirectory of your application. These assemblies are automatically linked in by default, based on the <assemblies> subsection of the <compilation> section of the Machine.config configuration file, which contains the following tag:

<add assembly="*"/>

This specifies that ASP.NET should link in any assemblies in the bin subdirectory. Note also that any other assemblies specified by an <add> tag in the <assemblies> subsection do not require linking with the @ Assembly directive.

@ OutputCache

The @ OutputCache directive is used to specify that the rendered output of the page or user control in which it appears should be cached, and it specifies the attributes that determine the duration of caching, the location of the cached output, and the attributes that determine when a client will receive freshly rendered content rather than the cached content. Output caching in user controls can be especially useful when some of the content in a page is relatively static, but other content is frequently updated, making it a poor candidate for caching. In a case like this, you could move the static content into a user control and use the @ OutputCache directive to cache its content, while leaving the rest of the page to be dynamically generated with each request.

The @ OutputCache directive's attributes are listed in the following table.

@ OutputCache Attributes 

Attribute Value Purpose
Duration Number of seconds. (Required.) Specifies the time, in seconds, for the page or control to be cached.
Location One of the following:
Any
Client
Downstream
None
Server
(Required.)
Specifies the location where cached output should be stored.
VaryByCustom Any valid text string. Specifies a custom string by which to vary the output cache. If browser is used, output caching will vary based on the browser name and major version. If you want to vary by HTTP request data other than the requesting browser, you will need to override the GetVaryByCustomString method of the HttpApplication class in Global.asax in order to implement your custom string.
VaryByHeader List of valid HTTP headers, separated by semicolons. Specifies one or more HTTP headers to be used to vary the output cache. When a request is received with a value for the specified HTTP header(s) that does not match that of any of the cached pages, a new version of the page will be rendered and cached. This attribute may not be used with user controls.
VaryByParam List of querystring keys or form field names, separated by semicolons, or one of the following:
none
*
(Required.)
Specifies one or more names of either querystring keys passed with a GET request, or form field names passed with a POST request to be used to vary the output cache. When a request is received with a value for one of the specified parameters that does not match that of any of the cached pages, a new version of the page will be rendered and cached. If the value of this attribute is set to none, the output cache will not vary based on GET and POST parameters. If the value is set to *, the output cache will vary by all GET and POST parameters.
VaryByControl List of properties exposed by a user control, separated by semicolons. Specifies one or more properties exposed by a user control to be used to vary the output cache. When a request is received with a value that does not match the specified property of any of the cached pages, a new version of the page will be rendered and cached. This attribute may only be used for output caching with user controls, not with ASP.NET pages.

Enabling Output Caching

For pages or user controls whose content does not change frequently, output caching can provide a simple and powerful way to improve the performance of your application. With output caching enabled, requests that match the parameters of the cached pages will be served from the cache, which is much faster than rendering the page again. Use these steps to enable output caching on an Web Forms page:

  1. Open the desired page in a text editor, or in Visual Studio .NET.
  2. Add the @ OutputCache directive with, minimally, the required Duration, Location, and VaryByParam attributes.
  3. <%@ OutputCache duration="60" location="Any" VaryByParam="*" %>
    
  4. Save the file. With these values for the attributes, the output of the page will be cached for 60 seconds. Any GET/POST requests with parameters that do not match an existing cached version of the page will be served a freshly rendered version of the page, which will then be cached.

For more information on output caching and using the ASP.NET cache engine to store arbitrary data, refer to Chapter 14.

@ Reference

The @ Reference directive allows you to dynamically load user controls by referencing the file name of the desired control and then using the Page.LoadControl method to load the control at runtime. The @ Reference directive directs the ASP.NET runtime to compile and link the specified control to the page in which it is declared. You'll see an example of using the @ Reference directive later, when this chapter discusses user controls.

The Page Class

The Page class provides much of the functionality of an ASP.NET page. Pages can take advantage of this functionality because every page derives from the Page class and inherits all of the methods and properties that it exposes. Some of the more notable members of the Page class, which resides in the System.Web.UI namespace, are included in the following list.

  • The ASP Intrinsic objects (Application, Session, Request, Response, Server, and Context) are implemented in ASP.NET as class instances, which are exposed as properties of the page object. For example, the Server functionality is provided by a class called HttpServerUtility. Because the instance of HttpServerUtility is exposed as the Server property of the Page class, you can call its methods (Server.Transfer, for example) just as you could in classic ASP.
  • The Controls collection provides access to the collection of controls defined for the page. As you'll see later in this chapter, you can use this collection to add or modify controls on a page using this collection.
  • The IsPostBack property allows you to determine whether the current request is a GET request or a POST request resulting from the current page being posted back to itself. This property is very useful in deciding what to do when loading a Web Forms page, as you'll see later in this chapter.
  • The User property provides access to information about the currently logged-in user.
  • The Cache property provides access to the ASP.NET cache engine, allowing data to be cached for later retrieval.
  • The FindControl method allows you to locate a control contained in the page's Controls collection by specifying its ID property.
  • The ViewState property provides access to a state dictionary (based on the StateBag class) that allows you to store information in Key/Value pairs. This information is passed with each request as a hidden HTML form field.
  • The ClearChildViewState method allows you to delete all viewstate information for any child controls on the page. This is useful if you want these controls to maintain their state most of the time, but you want to clear the state programmatically under specific circumstances.

Many other properties and methods are exposed by the Page class. A substantial number of these are inherited from the Control class, from which the Page class is derived, or the Object class, from which the Control class (and ultimately, every other class) is derived. This is an example of how inheritance allows you to build a very rich object model.

There are two methods by which an ASP.NET page is inherited from the Page class. The first is adding the @ Page directive to an .aspx file, which automatically makes all of the properties and methods of the Page class available to any code written in the page. The second method, which is discussed in more detail later in this chapter, is inheriting from the Page class in a code-behind class that is associated with the page by either the Src or Inherits attribute. This not only makes all of the members of the Page class available to the code-behind class, but it also allows ASP.NET to combine the code in the Web Form's .aspx file with the code in the code-behind class file into a single compiled class at compile time. This single compiled class contains all of the methods and properties exposed by the Page class, as well as any methods and properties implemented by your code.

Any of the members of the Page class can be called within code in a page without explicitly using the page name. For example, to write text to the browser using the Write method of the Response object, you would use the following code:

<%
Response.Write("Hello, World!")
%>

You could also use

<%
Page.Response.Write("Hello, World!")
%>

But it is not necessary to add the Page property because the Response property and the other Page members are exposed directly.

Writing Code in Web Forms

One of the strengths of classic ASP was that it gave you a lot of flexibility in writing your code. You could write your code inline with the HTML markup, as a part of <% %> render blocks. You could write your code in subroutines in render blocks. And you could write your code in <script> declaration blocks, either as arbitrary code or as subroutines.

While this flexibility made it very easy to create ASP pages, it was also a major weakness of classic ASP because it allowed for some sloppy coding. It was far too easy to write unmanageable spaghetti code, with some code inline, some code in subroutines, etc. In addition, although code in render blocks in classic ASP was executed in a linear fashion, arbitrary code (code not contained in a subroutine) in a <script> block was not. This often resulted in confusion, because sometimes this code was executed out of sequence with what developers expected.

ASP.NET solves these problems by imposing limitations on what types of code may be written, and where. As with classic ASP, there are still two ways to write code within a Web Forms page: <script> blocks and <% %> render blocks.

Using <script> Code Declaration Blocks

As mentioned, in classic ASP, you could write pretty much any code you wanted (property and method definitions, arbitrary code, etc.) in a <script> block using the runat="server" attribute. The problem was that you couldn't be sure when any arbitrary code in the <script> block would execute, relative to the code in the rest of the page. For this reason, ASP.NET does not allow you to use arbitrary code within <script> blocks, which are now referred to as code declaration blocks, to emphasize their purpose of declaring properties and methods.

So if you want to call Response.Write within a code declaration block, you need to wrap that call within a method declaration. The following code will work:

<script language="vb" runat="server">
Sub SayHello
Response.Write("Hello, World!")
End Sub
</script>

The following code will cause an error:

<script language="vb" runat="server">
Response.Write("Hello, World!")
</script>

Likewise, you can declare a local member variable in a declaration block, but you may not assign to it outside of a defined method. So the following code will work:

<script language="vb" runat="server">
Dim Name As String
Sub SetName
Name = "Andrew"
End Sub
</script>

But the following will cause an error:

<script language="vb" runat="server">
Dim Name As String
Name = "Andrew"
</script>

There is one exception to the variable assignment rule. You can initialize the value of a variable by assigning a value as part of the variable declaration, as follows:

<script language="vb" runat="server">
Dim Name As String = "Andrew"
</script>

The language attribute of the <script> block is optional. If it is omitted, the value will default to the language specified by the @ Page directive's language attribute. If no language attribute has been specified for the @ Page directive, the value will default to VB.

Using ASP <% %> Code Render Blocks

Like <script> blocks, <% %> render blocks in classic ASP were pretty much "anything goes." In many cases, this led to sloppy programming habits and hard-to- maintain code. ASP.NET solves these problems by not allowing anything other than inline code and expressions in render blocks. This means that you can no longer place method definitions in a render block. So the following code will cause a compiler error:

<%
Sub SayHello
Response.Write("Hello, World!")
End Sub
%>

Whereas the following code will work fine:

<%
Response.Write("Hello, World!")
%>

Compatibility with Classic ASP

Clearly, one of the issues that arises from these changes is that a good deal of code written in classic ASP will not be compatible with the restrictions on the use of code declaration and render blocks. For this reason, it is a good idea to examine any classic ASP code that you are considering migrating to ASP.NET for these incompatibilities, so that you can address them before making the migration. (And discovering too late that the code won't work!)

Creating and Using User Controls

User controls are a new feature of ASP.NET that provides a simple and fast method for getting reuse out of your presentation code. User controls can also dramatically increase performance when used in conjunction with the OutputCache directive described previously. They are sometimes referred to as declarative controls (as opposed to server controls, which are compiled controls).

At their simplest, user controls consist of HTML markup and/or ASP.NET code persisted in a file with the .ascx file extension. As you saw earlier in this chapter, developers of user controls can also add the @ Control directive to specify aspects of how the user control will behave. Unlike Web Forms pages, user controls cannot be called directly. Instead, they must be used in an existing page.

User controls can contain most, but not all, of the same elements that can be used in Web Forms pages. For example, user controls should not contain <html>, <body>, or <form> elements because presumably they already exist in the page in which the user control is used. It's also a good idea to at least add the @ Control directive, along with its ClassName attribute, as follows:

<%@ Control ClassName="MyClass" %>

Adding the ClassName attribute allows the user control to be strongly typed when added to a page programmatically (as opposed to declaratively).

Creating a User Control

Creating a user control is fairly straightforward.

  1. Using your favorite text editor, create a new file called Hello.ascx and save it to a folder that is set up as an IIS virtual directory.
  2. Add the following code to the file:
  3. <%@ Control ClassName="Hello" %>
    <script language="vb" runat="server">
    Private _name As String = ""
        Public Property Name As String
    Get
    Return _name
    End Get
    Set
    _name = Value
    End Set
    End Property
       Public Sub SayHello()
    Label1.Text = "Hello, " & _name & "!"
    End Sub
    </script>
    <asp:Label id=Label1 runat="server"></asp:label>
  4. Save the file.

This code declares a private string variable called _name; a Property procedure called Name that will be used to set and retrieve the value of the _name variable from outside the user control; and a Sub procedure called SayHello that sets the Text property of the Label server control defined in the last line of the user control code.

In order to use this control, you need to add it to a Web Forms page. There are two ways to do this: declaratively and programmatically. The declarative method is simpler, but the programmatic method gives you better runtime control.

Adding a User Control to a Page Declaratively

To use a user control in a Web Forms page, you need to make the control available to the page, and implement the control on the page. As described in "Using Directives" on page 214, user controls can be made available to a page using either the @ Register directive or the @ Reference directive, depending on whether you are adding the control declaratively or programmatically. If you want to add the control declaratively, you need to use the @ Register directive to set up the tag syntax for the control.

  1. Create a new Web Forms page called HelloContainer.aspx and save it in the same folder as Hello.ascx.
  2. Add the following code to the file:
  3. <%@ Page Language="vb" %>
    <%@ Register TagPrefix="ASPNETSbS" TagName="Hello" Src="hello.ascx" %>
    <html>
    <head>
    </head>
    <body>
    </body>
    </html>
  4. Save the file, but don't close it. You'll be adding to it in a moment.

Using the @ Register directive allows you to declare a user control instance (thus, declarative) using a tag-based syntax similar to HTML. The TagPrefix and TagName attributes in the @ Register directive determine the syntax for the tag. Here's how to add an instance of the Hello.ascx user control to the page:

  1. Add the following line to the <body> section of the HelloContainer.aspx page:
  2. <body>
    
       <ASPNETSBS:Hello id="MyHello" runat="server"/>
    
    </body>
    
  3. Save the file, but again, don't close it.

This tag adds an instance of the user control defined in Hello.ascx to the page and gives it the ID MyHello. It also provides a placeholder in the page for any output generated by the user control.

The last thing you need to do is set the Name property of the user control and call its SayHello method, which you'll do by adding a Page_Load method to the page. Note that you can also define a Page_Load method in the user control to have the user control take care of setting its property and calling its method. To set the property and call the method when your Web Forms page is loaded, follow these steps:

  1. Add the following code in the <head> section of the HelloContainer.aspx page, as shown here:
  2. <head>
    <script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
    MyHello.Name = "Andrew"
    MyHello.SayHello
    End Sub
    </script>
    </head>
  3. Save the page.
  4. Browse HelloContainer.aspx. You can do this either by entering the URL for the virtual directory in which you saved the file, plus the file name, into the browser address box, or by opening Internet Services Manager, locating the folder containing the page, right-clicking the page, and selecting Browse, as shown in the following figure.
  5. (Image Unavailable)

    The output should appear similar to that in the following figure.

    (Image Unavailable)

Adding a User Control to a Page Programmatically

The steps for adding a control to a page programmatically are somewhat similar, but a bit more involved than adding a control declaratively. You still need to make the control available to the page. For controls that are to be added programmatically, you can do this with either the @ Register directive, as in the previous example, or the @ Reference directive. Since the @ Register directive is more commonly used for declarative controls, use the @ Reference directive.

  1. Create a new Web Forms page called HelloReference.aspx and save it in the same folder as Hello.ascx.
  2. Add the following code to the file:
  3. <%@ Page Language="vb" %>
    <%@ Reference Control="hello.ascx" %>
    <html>
    <head>
    </head>
    <body>
    </body>
    </html>
  4. Save the file, but don't close it.

The @ Reference directive tells ASP.NET to compile and link the user control hello.ascx with the page when it is compiled. This makes the control available to be added to the page. Since you're not going to be adding a tag within the HTML markup for the control's output, take advantage of a special server control called the Placeholder control. As the name suggests, this allows you to put a placeholder in the HTML markup to which you can add controls later. In this way, you can decide precisely where you want the output from the control to appear. Here's how to add the Placeholder control:

  1. Add the following line to the <body> section of the HelloReference.aspx page:
  2. <body>
    <asp:placeholder id="HelloHolder" runat="server"/>
    </body>
  3. Save the file, but don't close it yet.
Finally we need to add the control to the page, and add it to the Controls collection of the Placeholder control, which will place the output of the control where we want it. Then we'll set the Name property of the control, and call the SayHello method, just as we did before.
  1. Add the following code in the <head> section of the HelloReference.aspx page:
  2. <head>
    <script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
    Dim MyHello As Control = LoadControl("hello.ascx")
    HelloHolder.Controls.Add(MyHello)
    CType(MyHello, Hello).Name = "Andrew"
    C Type(MyHello, Hello).SayHello
    End Sub
    </script>
    </head>
  3. Save the page.
  4. Browse HelloReference.aspx. Either type the URL for the virtual directory in which you saved the file, plus the file name, into the browser address box, or use the Internet Services Manager as shown in the previous example. The output of the page should be the same as in the previous figure.

Comparing User Controls to Include Files:
User controls perform a similar function to server-side includes in classic ASP, but they're considerably more powerful because of the level of integration with the page model. A user control can have its own controls, and it can save the viewstate of its controls or its own viewstate. This allows the user control to maintain its state across multiple calls without any effort on the part of the page containing the user control. User controls can expose both properties and methods, making them easy to understand for developers who are used to components.

Include files are still available in ASP.NET, mainly for backward compatibility with classic ASP. For new applications, it makes more sense to use user controls, given their advantages.


Using Server Controls

Like user controls, ASP.NET server controls allow developers to reuse functionality. ASP.NET comes with a wide variety of built-in server controls that provide a great deal of functionality that developers can reuse in their applications. These include controls that provide server-side equivalents of standard HTML controls, more advanced controls that mimic Visual Basic–style controls, and validation controls that allow powerful and robust validation of data entry. Developers can also create custom server controls to provide their own reusable functionality.

The code for adding a server control to a page is simple and straightforward, particularly for the built-in server controls. This section demonstrates how to add an HTML control (a server control from the System.Web.HtmlControls namespace), a Web control (a server control from the System.Web.WebControls namespace), and a custom server control to a page. The differences between HTML controls and Web controls are discussed in detail in Chapter 10. The creation of custom server controls is discussed in Chapter 12.

One of the advantages of the built-in server controls is that they are available from any Web Forms page. You don't need to make them available via the @ Register or @ Reference directives, as is necessary with user controls (as well as with custom server controls, as you'll see later in this section). This means that to use a server control, you need only add the appropriate tag to your page.

Adding an HTML Control to the Page

HTML controls use the same syntax as client-side HTML elements, with one addition: the runat="server" attribute. So in order to add an HtmlInputButton control (a server control that maps to the HTML <input type="submit">, <input type="button">, or <input type="reset"> elements) to a page, follow these steps:

  1. Using your favorite text editor, create a new page in the same folder as the previous examples. Name the page ServerControls.aspx.
  2. Add the following code to the page:
  3. <%@ Page Language="vb" %>
    <html>
    <head>
    </head>
    <body>
    <form runat="server">
    <input id="NameButton" type="submit" runat="server"/>
    </form>
    </body>
    </html>
  4. Save the page, but don't close it. You'll use this page for further examples.

By adding the runat="server" attribute to the HTML <input> element, you've created a full-fledged server control that can now be manipulated programmatically through server-side code. Note that to make it easier to program against your server controls, you should always give them an id attribute, which specifies the name you'll use to identify the control in server-side code. You've also added a server-side <form> to wrap your server control, which causes the page to be posted back to the server when the button is clicked.

Adding a Web Control to the Page

Web controls use a slightly different syntax than HTML controls. It's similar to the syntax used for adding a user control to the page declaratively, except that instead of defining your own tag prefix, all Web controls use the prefix asp. For example, the tag for adding a TextBox Web control to the page would be <asp:TextBox id="myTextBox" runat="server"/>.


NOTE:
If you're familiar with XML namespaces, you may notice the similarity between the tag prefixes used for Web controls, user controls, custom server controls, and XML namespaces. This is no coincidence, since the implementation of the tag syntax for server controls and user controls is based on XML namespaces.

Likewise, user control and server control tags must also follow the syntax rules for XML tags, which require an opening and closing tag for any tag that contains text or child tags, such as the Label Web control, which allows you to set its Text property by placing the desired text between the opening and closing <asp:label> tags. A closing / in a single tag may be used for tags that do not contain text or child tags, such as the HtmlInputButton HTML control.


To add a TextBox Web control and two Label Web controls, follow these steps:

  1. Add the following tags to the server-side form of the ServerControls.aspx page created in the previous example:
  2. <asp:Label id="NameLabel" runat="server">Name: </asp:Label>
    <asp:TextBox id="NameTextBox" runat="server"/>
  3. Add another Label control just below the closing </form> tag. Set the id attribute to "HelloLabel". Use the single-tag syntax. The finished <body> section of the page should look like the following:
  4. <body>
    <form runat="server">
    <asp:Label id="NameLabel" runat="server">Name: </asp:Label>
    <asp:TextBox id="NameTextBox" runat="server"/>
    <input id="NameButton" type="submit" runat="server"/>
    </form>
    <asp:Label id="HelloLabel" runat="server"/>
    </body>
  5. Save the page, but don't close it.

Having added this code, you can enter text in the TextBox control and submit the page by clicking the button. But you still must add code to process text entered in the textbox. See "Event Handling" on page 240 for more information.


Server-Side Forms, Postbacks, and ViewState:
The term postback describes the ability of an ASP.NET page to make an HTTP POST request to itself, usually in response to a user clicking a button server control or interacting with another server control that initiates a postback. Postbacks are very useful because they allow a single page to both display UI elements, such as form fields for a user to fill in, and process the data entered by the user. The page developer can check the page-level IsPostBack property to determine whether the current request is the result of a postback, and then take appropriate action.

By default, server controls such as the TextBox and DropDownList Web controls automatically save their state from request to request using the viewstate facility built into ASP.NET.

Both the postback and viewstate facilities require the use of a server-side <form> to function. HTML controls and Web controls may be added to a Web Forms page without the a server-side <form> element wrapping the controls, and the controls will still function and can still be manipulated programmatically. But these controls will not be able to participate in postbacks, nor will they be able to save their state in the page's viewstate. For this reason, when using server controls, most often you'll want to wrap the controls in a server-side <form>.


Adding a Custom Server Control to the Page

Custom server controls use essentially the same tag syntax as user controls, but a slightly different form of the @ Register directive to make the custom control available to the page. Whereas the @ Register directive for a user control contains TagPrefix and TagName attributes to specify the tag that will be used to invoke the user control, and an Src attribute that points to the .ascx file containing the user control, the @ Register directive for a custom server control contains only the TagPrefix attribute, while the tag name for the control is supplied by the class name of the class that defines the server control. The location of the custom server control is supplied by an Assembly attribute containing the name of the compiled assembly containing the control definition. This assembly must reside either in the Web application's bin subdirectory or in the global assembly cache. The @ Register directive for a custom server control also requires a Namespace attribute with the namespace that contains the class defining the custom control.

Assuming you had a custom server control with a class name of MyControlClass in a namespace called MyNS in an assembly called MyControl.dll, the @ Register directive for the control would look like the following:

<%@ Register TagPrefix="MyPrefix" Namespace="MyNS"
Assembly="MyControl" %>

The tag used to invoke the control would look like the following:

<MyPrefix:MyControlClass id="MyControlID" runat="server"/>

For more information on the standard server controls included with ASP.NET, refer to Chapter 10. Creating and using custom server controls is covered in much greater detail in Chapter 12.

Event Handling

One of the biggest differences between classic ASP and ASP.NET is the execution model. In classic ASP, pages were executed in a top-to-bottom fashion. That is, with the exception of detours to execute functions defined in the page, classic ASP pages were procedural rather than event-driven, like Visual Basic programs.

ASP.NET changes that by bringing event-driven programming to Web development through server controls and postbacks. At runtime, the code in a Web Form, as well as in any code-behind class associated with that Web Form, is compiled into an assembly. When executed, the code in that assembly fires events that you can handle, both those exposed by the Page class and those that are fired by server controls that have been added to the page.


Page Processing Stages:
A Web Forms page goes through the following processing stages:
  • Init Page and control settings are initialized as necessary for the request.
  • LoadViewState Server control state that was saved to viewstate in an earlier request is restored.
  • LoadPostData Any data returned in server control form fields is processed, and the relevant control properties are updated.
  • Load Controls are created and loaded, and control state matches the data entered by the client.
  • RaisePostDataChangedEvent Events are raised in response to changes in control data from the previous request to the current request.
  • RaisePostBackEvent The event that caused the postback is handled, and the appropriate server-side events are raised.
  • PreRender Any changes that need to be made prior to rendering the page are processed. Any processing after this point will not be rendered to the page.
  • SaveViewState Server control state is saved back to the page's viewstate prior to tearing down the controls.
  • Render Control and page output is rendered to the client.
  • UnLoad The page and its constituent controls are removed from memory on the server.

Of these stages, you can add page-level event handlers for the Init, Load, PreRender, and UnLoad events. These handlers are typically named Page_Init, Page_Load, Page_PreRender, and Page_UnLoad, respectively. For other stages, such as the LoadViewState, SaveViewState, and Render stages, you can override the appropriate method to customize the processing of these stages.


Some events, such as those fired by the page, are fired automatically as certain stages of page processing occur. Others, such as those associated with server controls, are actually triggered on the client (such as a user clicking a button server control) but are fired and handled on the server when the page is posted back to the server. Because the page is reloaded and the control state is restored with each postback, to the client it appears as though the page is there throughout the client's interaction with it, and the application appears to operate much like a Visual Basic form-based application.

Handling Page Events

Each stage in the processing of a Web Forms page fires an event that allows you to perform processing of your own during that stage.

To illustrate this concept, let's finish up the ServerControls.aspx page that you started in the previous example by adding an event handler to use the text the user enters in the TextBox server control.

  1. If it's not already open, open the ServerControls.aspx page you created earlier.
  2. Add the following code to the <head> section of the page:
  3. <head>
    <script runat="server">
    Sub Page_Load(Sender As Object, E As EventArgs)
    If IsPostBack Then
    HelloLabel.Text = "Hello, " & _
    Server.HtmlEncode(NameTextBox.Text) & "!"
    End If
    End Sub
    </script>
    </head>
  4. Save the page, and then browse to it by entering the appropriate URL in a browser window, as shown in the following figure, or using Internet Services Manager.
  5. (Image Unavailable)

  6. Enter a name in the textbox, and then click the Submit Query button. After the page is posted back, the output should look similar to the following figure.
  7. (Image Unavailable)

In the preceding code, you added an event handler for the Page_Load event. This event handler is called when the Load stage of the page processing is reached. In the event handler, you check the page-level property IsPostBack to determine if the page has been posted back as a result of a client action (clicking the button in this case). If it has, you set the Text property of HelloLabel to the desired text, which includes the text the user entered in the textbox. Notice that you use the Server.HtmlEncode utility method to encode the text entered by the user. This helps prevent nasty users from entering <script> tags or other HTML content to do something you don't want them to do. Using the HtmlEncode method means that any such content will be written out using HTML entity equivalents of characters such as less than (<), greater than (>), and quotation marks.


IMPORTANT:
The preceding code assumes that the AutoEventWireup attribute of the page has been set to true. Normally, you won't need to set this manually, since this is the default setting that is inherited from the <pages> configuration section in Machine.config. However, pages created by Visual Studio .NET have the AutoEventWireup attribute in their @ Page directive set to false. This means that all event handlers in these pages must be manually wired to the events that they are to handle. You'll learn about manually wiring events in Chapter  .

Handling Control Events

Handling events raised by controls is fairly straightforward. There are two steps. The first is similar to the way that you handle page events, only instead of naming the event handler Page_eventname, you use the syntax controlname_eventname. This is similar to how event handlers are constructed in Visual Basic. The second step is to map the event raised by the control to the event handler using an attribute of the control's tag.

For example, if you wanted to add an event handler to ServerControls.aspx to handle the TextChanged event of the TextBox server control, you would add the following code to the <script> block in ServerControls.aspx:

Sub NameTextBox_TextChanged(Sender As Object, E As EventArgs)
HelloLabel.Text &= " This text is different!"
End Sub

And then you would add the following attribute to the NameTextBox server control tag:

<asp:TextBox id="NameTextBox" onTextChanged="NameTextBox_TextChanged"
runat="server"/>

Notice that here you use the &= operator to add text to the Text property of HelloLabel. The &= operator is shorthand for the following:

HelloLabel = HelloLabel & " This text is different!"

If you add this code to ServerControls.aspx and run it, the output when the text is changed will look like the following figure.

(Image Unavailable)

Handling Page Errors

While using structured exception handling may be useful for catching exceptions that are expected (see Chapter 4), there are times when you want to handle errors at the page level. This is possible through a special event handler called Page_Error. The Page_Error event is raised whenever a page encounters an unhandled exception. Within the Page_Error event handler, you can examine the exception that occurred using the Server.GetLastError method and take appropriate action or display a friendly message to the user.

Page Runtime Structure

As discussed earlier, at runtime ASP.NET combines the code in the page and any associated code-behind class into a single class, and then it compiles that class and executes it on the server. In the process, ASP.NET builds a control tree containing all of the controls on the page, including LiteralControl server controls for each section of HTML text.


IMPORTANT:
When compiling a page, ASP.NET automatically creates controls that represent the HTML markup in the page, using the LiteralControl server control class. This allows the HTML markup to be easily manipulated at runtime, and also allows greater flexibility in adding controls at runtime. If the page contains <% %> render blocks, however, ASP.NET will not create controls to encapsulate the HTML markup. If you want to be able to manipulate the markup as LiteralControls, don't use <% %> render blocks.

At the top of the control tree is the control that represents the page, which has the ID __PAGE. Beneath that are any child controls that belong to the page's Controls collection. Each child control, depending on the type of control, may in turn have its own Controls collection containing child controls, and so on. This structure makes it much easier to find and manipulate controls at runtime.

Viewing the Page Control Tree

The easiest way to view the control tree for a page is to turn on tracing for the page. To view the control tree for the ServerControls.aspx page you created earlier, follow these steps:

  1. Open ServerControls.aspx in a text editor.
  2. Add the Trace attribute to the @ Page directive and set its value to true. The completed directive is as follows:
  3. <%@ Page Language="vb" Trace="true" %>
    
  4. Save the file and browse the page. The control tree section of the ServerControls.aspx trace output is shown in the following figure. Notice that where a control has been given an explicit ID through its id tag attribute, that ID is used in the control tree.
  5. (Image Unavailable)

Adding and Manipulating Controls at Runtime

Thanks to the control tree built by ASP.NET at runtime, you can easily add, remove, or manipulate controls at runtime, even if you don't know the name of a control. For example, you can use the Add method of the page's Controls collection to add a new control to the page at runtime.

Dim MyTextBox As New TextBox
Page.Controls.Add(MyTextBox)

If you want to place the new control at a particular position in the control tree, you can use the AddAt method instead.

Dim MyTextBox As New TextBox
Page.Controls.AddAt(2, MyTextBox)

To remove a control by name, you can use the Remove method.

Page.Controls.Remove(MyTextBox)

And to remove a control by index, you can use RemoveAt.

Page.Controls.RemoveAt(2)

To locate a particular control by ID, you can use the FindControl method of the page or control containing the control you're looking for.

MyControl = Page.FindControl("MyTextBox")

Note that because FindControl returns an object of type Control (rather than of the specific type of control used), you will need to cast to the appropriate control type before using properties or methods that are specific to that control type.

Using Code-Behind in Web Forms

In addition to the changes in <script> blocks and <% %> render blocks in ASP.NET that make it easier to write clean code, ASP.NET introduces an entirely new concept called code-behind, which allows developers to entirely separate executable code from their HTML markup and server control tags.

A code-behind for a Web Form consists of a file containing a class derived from the Page class, and optionally contained within a namespace. The Web Form page then inherits from the code-behind class at runtime, allowing both the Web Form and its code-behind class to be compiled into a single assembly for execution.

Separating Code from UI

To show you how this works, let's use the ServerControls.aspx page one last time. To use code-behind with this page, follow these steps:

  1. Open ServerControls.aspx in a text editor.
  2. Using a text editor, create two new files, ServerControls_cb.aspx and ServerControls_cb.vb.
  3. Copy all of the text from ServerControls.aspx and paste it into ServerControls_cb.aspx, and then close ServerControls.aspx.
  4. Cut all of the code contained within the <script> block in ServerControl_cb.aspx and paste it into ServerControls_cb.vb, and then remove the <script> tags.
  5. Add Src and Inherits attributes to the @ Page directive in ServerControls_cb.aspx to help ASP.NET locate the code-behind class file.
  6. <%@ Page Language="vb" Src="ServerControls_cb.vb"
    Inherits="ServerControls" %>
  7. Save ServerControls_cb.aspx. The final page should look like the following:
  8. <%@ Page Language="vb" Src="ServerControls_cb.vb"
    Inherits="ServerControls" %>
    <html>
    <head>
    </head>
    <body>
    <form runat="server">
    <asp:Label id="NameLabel" runat="server">Name: </asp:Label>
    <asp:TextBox id="NameTextBox"
    onTextChanged="NameTextBox_TextChanged" runat="server"/>
    <input id="NameButton" type="submit" runat="server"/>
    </form>
    <asp:Label id="HelloLabel" runat="server"/>
    </body>
    </html>
  9. Add the following code to ServerControls_cb.vb, before the text that you pasted in step 4:
  10. Imports System
    Imports System.Web
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Public Class ServerControls
    Inherits Page
    Public HelloLabel As Label
    Public NameTextBox As TextBox
  11. Add an End Class statement to ServerControls_cb.vb, after the text that you pasted in step 4. The finished code should look like the following:
  12. Imports System
    Imports System.Web
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    Public Class ServerControls
    Inherits Page
    Public HelloLabel As Label
    Public NameTextBox As TextBox
      Sub Page_Load(Sender As Object, E As EventArgs)
    If IsPostBack Then
    HelloLabel.Text = "Hello, " & _
    Server.HtmlEncode(NameTextBox.Text) & "!"
    End If
    End Sub
      Sub NameTextBox_TextChanged(Sender As Object, E As EventArgs)
    HelloLabel.Text += " This text is different!"
    End Sub
    End Class
  13. Save both files, and browse ServerControls_cb.aspx. The output should be the same as in the previous figure.

In this example, you've separated the event handling code into a code-behind class file. To make this work, you've had to take some extra steps. You added the Imports statements to the code-behind file to allow you to use the names of classes such as Label and Textbox without explicitly adding their namespaces. This is essentially the same as using the @ Import directive described earlier in this chapter. One difference is that unlike Web Forms pages, code-behind class files must explicitly import any of the namespaces for classes to be used in the file (unless all class references use the fully qualified name for the class).

You also added the Class statement, to define the class ServerControls, and the Inherits statement, which specifies that you want the ServerControls class to be derived from the Page class. Then you declared two Public variables, one for each server control that you want to access in your event-handler code. Finally, you wrapped up the code-behind with an End Class statement to close out the class.

In the Web Form, you associated ServerControls_cb.vb with ServerControls_cb.aspx by adding the Src and Inherits attributes to the @ Page directive. The Src attribute tells ASP.NET where to locate the class file for the code-behind, and the Inherits attribute tells ASP.NET which class (or namespace and class) you want to inherit from in the code-behind file.

While there are a few more steps involved in creating a page that uses code- behind compared to writing all of your code in a Web Form, the resulting code is generally much easier to maintain and update. For complicated pages, this alone can make it well worthwhile to use code-behind.

Chapter 9 Quick Reference

To Do This
Modify the runtime behavior of an ASP.NET Web Form Add the @ Page directive to the page and set the desired attributes.
Use classes by name without explicitly specifying their namespace In a Web Form, add the @ Import directive, with the namespace attribute specifying the namespace to import. In a Visual Basic .NET code-behind file, add the Imports statement with the desired namespace. In a C# code-behind file, add the using statement with the desired namespace (such as using System.Web;).
Make a user control or custom server control available for use on a Web Form Add the @ Register directive to the page, and set the appropriate attributes.
Enable output caching Add the @ OutputCache directive to the page, and set the desired attributes.
Create a user control Create a file with the .ascx extension containing the desired HTML markup, server controls and code. User controls should not contain <html>, <body>, or <form> elements. Optionally, add the @ Control directive to modify the runtime behavior of the control.
Write server-side functions in a Web Forms page Create a <script> block with the runat="server" attribute and place the functions within it.
Handle page-level events Add an event handler with the appropriate signature (such as Page_eventname) to the server <script> block.
Read More Show Less

Customer Reviews

Average Rating 2
( 5 )
Rating Distribution

5 Star

(0)

4 Star

(0)

3 Star

(1)

2 Star

(2)

1 Star

(2)

Your Rating:

Your Name: Create a Pen Name or

Barnes & Noble.com Review Rules

Our reader reviews allow you to share your comments on titles you liked, or didn't, with others. By submitting an online review, you are representing to Barnes & Noble.com that all information contained in your review is original and accurate in all respects, and that the submission of such content by you and the posting of such content by Barnes & Noble.com does not and will not violate the rights of any third party. Please follow the rules below to help ensure that your review can be posted.

Reviews by Our Customers Under the Age of 13

We highly value and respect everyone's opinion concerning the titles we offer. However, we cannot allow persons under the age of 13 to have accounts at BN.com or to post customer reviews. Please see our Terms of Use for more details.

What to exclude from your review:

Please do not write about reviews, commentary, or information posted on the product page. If you see any errors in the information on the product page, please send us an email.

Reviews should not contain any of the following:

  • - HTML tags, profanity, obscenities, vulgarities, or comments that defame anyone
  • - Time-sensitive information such as tour dates, signings, lectures, etc.
  • - Single-word reviews. Other people will read your review to discover why you liked or didn't like the title. Be descriptive.
  • - Comments focusing on the author or that may ruin the ending for others
  • - Phone numbers, addresses, URLs
  • - Pricing and availability information or alternative ordering information
  • - Advertisements or commercial solicitation

Reminder:

  • - By submitting a review, you grant to Barnes & Noble.com and its sublicensees the royalty-free, perpetual, irrevocable right and license to use the review in accordance with the Barnes & Noble.com Terms of Use.
  • - Barnes & Noble.com reserves the right not to post any review -- particularly those that do not follow the terms and conditions of these Rules. Barnes & Noble.com also reserves the right to remove any review at any time without notice.
  • - See Terms of Use for other conditions and disclaimers.
Search for Products You'd Like to Recommend

Recommend other products that relate to your review. Just search for them below and share!

Create a Pen Name

Your Pen Name is your unique identity on BN.com. It will appear on the reviews you write and other website activities. Your Pen Name cannot be edited, changed or deleted once submitted.

 
Your Pen Name can be any combination of alphanumeric characters (plus - and _), and must be at least two characters long.

Continue Anonymously
Sort by: Showing all of 5 Customer Reviews
  • Anonymous

    Posted April 7, 2003

    Decent Book

    Thought book was good at intriducing new controls and writing custom controls.I think if you have developed in VB or ASP, this is a good book to get. It talks a lot about security, which is good but slightly overwhelming. I would recommend.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted January 5, 2003

    Do Not Buy This Book

    This book was a huge disappointment. I expected the book to teach ASP.Net "STEP BY STEP". I bet the first 180 pages is cut-and-paste from MSDN . Covering highly technical aspects of ASP.NET such as the security model early on was very suprising and not enlightening when you know nothing about ASP. I expected much more from MS Press and am going to send them a comment after I clear this page.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted August 19, 2002

    Major Disappointment Don't Waste Your Money

    I was looking for a beginning book to learn how to create ASP.Net pages and all I got was a book that told what tags you could use in ASP.Net. This book might be ok for a reference book if you already new ASP.Net, but it is not a Step by Step book. The book needs to show how to build a practial real world application, but doesn't even come close. Any person can do a simple 'Hello World' program and they dont need to waste money buying a worthless book!

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted October 7, 2002

    Waste of Time and Money

    If you are interested in how ASP used to work, you may enjoy this book. If you want to learn how to use ASP.NET, buy a different book. Usually the Step by Step books are pretty informative and guide you through understanding the application building process. This book leaves a lot to be desired in this arena. The book may be OK for a reference guide.

    Was this review helpful? Yes  No   Report this review
  • Anonymous

    Posted June 30, 2002

    Not a good Step by Step book

    I was looking for a book that would teach more towards how to use the VS.NET interface. This book is written mostly using Notepad. If you want a book to teach you ASP.NET using the interface, than this is NOT it. I'm surprised that Microsoft produced a book that does not exploit the advantages of combining the Visual Studio interface. I use the interface and can out perform anything written in this book by just using Notepad. And ¿ I can do it in less time ¿ less bugs ¿ less coding ¿ with a better performing ASP web site. You can easily combine ASP with VB ¿ C++ or C# using the studio for very robust web pages. I wish someone would write an ASP.NET book using the VS.NET interface. So far, I have not found that book.

    Was this review helpful? Yes  No   Report this review
Sort by: Showing all of 5 Customer Reviews

If you find inappropriate content, please report it to Barnes & Noble
Why is this product inappropriate?
Comments (optional)