DekGenius.com
[ Team LiB ] Previous Section Next Section

3.1 Structuring an ASP.NET Page

An ASP.NET page is a declarative text file with the extension .aspx. A page consists of structural elements that can perform various operations—ultimately resulting in output of HTML or other MIME-type output that can be handled by the browser. An ASP.NET page can contain any or all of the following elements:

Page directives

Start with the @ symbol, followed by attribute/value pairs, and are used to specify page-level settings, such as the language used in the page or namespaces to be imported. For example, the following code specifies the C# programming language:

<%@ Page Language="C#" %>
Code declaration blocks

Consist of variable and member declarations within <script>...</script> tags, as follows:

<script language="C#" runat="server"> 
// code goes here
</script>

Note that there are limitations on what code you can place in <script> blocks in ASP.NET. In classic ASP, you can write executable code in a <script> block without wrapping that code in a subroutine. In ASP.NET, only variable declarations can be placed outside of a subroutine. Any other executable code not contained in a subroutine will result in an error.

Render code blocks

Used to write inline code and inline expressions within HTML elements. For example:

<% int i; %>
<H1><%=Heading%> </H1>

There are limitations on what code you can place in render blocks in ASP.NET. In classic ASP, you can define subroutines in render blocks. In ASP.NET, this is not permitted and results in an error.

Render blocks, while quite common in classic ASP, are less frequently used in ASP.NET, since they don't fit very well with the control-based, event-driven model introduced in ASP.NET. Support for render blocks is included for backward compatibility, but you should consider other alternatives carefully before using them in new development work, since extensive use of render blocks can make your pages difficult to debug.

Server-side comments

As always, comments are used for documentation and testing purposes. You can use them to prevent any code from executing, as in the following example:

<%-- Debugging Code To Be Removed --%>
Server controls

HTML and web controls declared with the runat="server" attribute/value pair. For example, the following code declares an HTML input server control and an ASP TextBox control:

<input type="text" id="MyText" runat="server">
<asp:TextBox id="Mytext" runat="server"/>
Server-side object tags

Used to declare and instantiate classic COM components and .NET classes. For example:

<object id="MyDataSet" class="System.Data.DataSet" runat="server">
Server-side include directives

Used to include any text file into your page. This was the primary code reuse mechanism in classic ASP. For example:

<!-- #Include file="TopNavigation.inc" -- >
<!-- #Include virtual="Menus.inc" -- >

In ASP.NET, the preferred means of sharing code is to create a shared class or server control that contains the functionality to be reused.

Server-side <form> element

Many server controls, including the TextBox control, must be contained within a server-side <form> tag pair with the runat="server" attribute:

<form runat="server">
   <asp:TextBox id="Mytext" runat="server"/>
   <asp:Button id="submit" runat="server"/>
</form>
Literal text

Any text that is not one of the elements listed previously is literal text and appears as it is in the output. This text also includes standard HTML tags. In the following example, "Name" is the literal text:

Name: <input type="text" id="txtName">

3.1.1 Using @ Directives

ASP.NET provides a number of @ directives—processing instructions that give the runtime and compiler additional information about how you want your code to run. These directives let you enable certain features, specify whether you want your pages to be based on the System.Web.UI.Page class (the default) or on a custom class that you name, etc. Under ASP.NET, @ directives can also have attributes that further enhance the configuration ability of the directive.

The list of @ directives in ASP.NET is greatly expanded from classic ASP, which provides only five directives (whose functionality is now provided by attributes of the @ Page directive). The following @ directives are available in ASP.NET:

@ Page

Arguably the most important directive, @ Page is included at the top of each ASP.NET page and allows you to set the page language and enable or disable such features as buffering, session state, and debugging. The @ Page directive has the following attributes:

AspCompat
<%@ Page AspCompat="True|False" %>

Specifies that the page should be executed in a single-threaded apartment (STA) to provide compatibility with COM components written in Visual Basic 6.0 (or other development tools that create only STA components). This attribute also provides access to unmanaged wrappers of the ASP intrinsic objects (Request, Response, etc.) for components that need access to these objects through ObjectContext or the OnStartPage method. By default, ASP.NET pages run in a multithreaded apartment, so enabling this feature by setting AspCompat to True can have a negative impact on the performance of your pages. The default value of this setting is False.

AutoEventWireup
<%@ Page AutoEventWireup="True|False" %>

Specifies that standard events (Page_Load, Page_PreRender, etc.) will be automatically wired to any handlers you provide. The default for this attribute (set in the machine.config configuration file) is True. Pages created with Visual Studio .NET have this attribute set to False, since Visual Studio creates the code to wire up events in a code-behind file for you. As such, turning on AutoEventWireup in a page created with Visual Studio .NET results in event handlers firing multiple times.

Buffer
<%@ Page Buffer="True|False" %>

Specifies whether or not ASP.NET page output should be buffered in memory and sent to the client when the entire page has been rendered, or until the End or Flush method of the HttpResponse class is called. (See Chapter 17 for more information on the HttpResponse class.) The default value is set to True.

ClassName
<%@ Page ClassName="classname" %>

Specifies the class name to be used for a dynamically compiled page. The default is the filename of the page, with the dot between the filename and the .aspx file extension replaced by an underscore (_). This class name appears as the top-level object in the Control Tree when ASP.NET tracing is enabled. See Chapter 10 for more information on tracing in ASP.NET pages and applications.

ClientTarget
<%@ Page ClientTarget="UserAgent/Alias" %>

Specifies that the page should be rendered using the defined capabilities of one of the browsers defined in the <clientTarget> section of the web.config or machine.config configuration files. Use of this attribute substitutes the user agent string defined in the <clientTarget> section for the one sent by the actual client browser, causing server controls that query browser capabilities to render for the browser type specified in the ClientTarget attribute. Note that setting this attribute to a value other than those defined in the <clientTarget> configuration section results in an exception.

Codebehind
<%@ Page Codebehind="path" %>

Specifies the code-behind class file that contains code for the page. This attribute is used by the Visual Studio .NET environment when building a project and is ignored by the ASP.NET runtime. Pages using the Codebehind attribute must compile their code-behind classes manually.

CodePage
<%@ Page CodePage="codepage" %>

Specifies the code page (a definition of how characters are mapped to the available bit patterns in each byte—code pages are used to define different character sets for different languages or regions) to be used for the page output.

CompilerOptions
<%@ Page CompilerOptions="options" %>

Specifies one or more command-line switches to be passed to the compiler for the language specified in the Language attribute. Behavior and availability of this attribute may vary depending on the language used for the page.

ContentType
<%@ Page ContentType="MIMEtype" %>

Specifies the HTTP content type sent as part of the HTTP headers for the response generated by the page. Can be set to any standard MIME type. This attribute is especially useful when returning types other than text/ html—such as when using an ASP.NET page to generate binary image output. In this case, you would set the ContentType attribute to the appropriate MIME type, such as image/jpeg. This attribute performs the same function as the ContentType property of the HttpResponse class. (See Chapter 17 for more information on the HttpResponse class.)

Culture
<%@ Page Culture="culturename" %>

Specifies the name of the culture to use for formatting numbers, dates, etc. For example, the culture name for United States English is en-US, which is also the default. Setting the Culture attribute to another culture name will result in alternate values, such as the date returned by the Visual Basic Now function being formatted for the specified culture.

Debug
<%@ Page Debug="True|False" %>

Specifies whether the page will be compiled with debug symbols. Enabling debugging allows the use of debuggers to step through code and provides more detailed information in the event of an exception, but also entails a performance penalty. For this reason, the Debug attribute should always be set to False in production applications. Note that the default value, which is False, is set in the <compilation> section of the machine.config configuration file.

Description
<%@ Page Description="textdescription" %>

Specifies a text description of the page. This attribute is ignored by the ASP.NET runtime.

EnableSessionState
<%@ Page EnableSessionState="True|False|ReadOnly" %>

Specifies whether the page supports session state. This attribute can be used to disable or delay the creation of sessions, which are used for state management. Setting this attribute to False when session state is not utilized can improve the performance of your application. If set to True, code within the page may read or write session values, and if no current session exists for the user, a new Session is created. If set to False, attempts to read or write session values result in an exception, browsing the page will not result in the creation of a new session, and if a session exists for the user, it will be unaffected. If set to ReadOnly, an existing session may be read from, but not written to, and browsing the page will not result in the creation of a new session. The default value, which is set in the <pages> section of the machine.config configuration file, is True.

EnableViewState
<%@ Page EnableViewState="True|False" %>

Specifies whether ViewState is supported for the page. ViewState is a new feature of ASP.NET that allows server control state (as well as developer-specified values) to be persisted across multiple requests to the page. ViewState is stored as a hidden form field containing an encoded text string representing the state of all controls for which ViewState is enabled; thus, any controls for which you want ASP.NET to manage state should be placed inside a server-side <form> tag pair. When ViewState is enabled for a page, individual controls can disable their own ViewState for better performance. Because ViewState is round-tripped between the server and client, you should be cognizant of the size of the ViewState field for the page. Disabling ViewState where it is not necessary (either at the page or control level) may improve performance. The default value, which is set in the <pages> section of the machine.config configuration file, is True.

EnableViewStateMac
<%@ Page EnableViewStateMAC="True|False" %>

Specifies whether ASP.NET should run a machine authentication check (MAC) on the ViewState contents to ensure that the ViewState was not tampered with on the client. This can make your page more secure, but may carry a performance penalty. The default value, which is set in the <pages> section of the machine.config configuration file, is False.

ErrorPage
<%@ Page ErrorPage="URL" %>

Specifies the URL of a page to which the user will be redirected if an unhandled exception occurs. This attribute should be considered a last line of defense in error handling and not a substitute for proper error/ exception handling. See Chapter 10 for more information on handling exceptions.

Explicit
<%@ Page Explicit="True|False" %>

Specifies whether pages written in Visual Basic .NET will be compiled using Option Explicit mode. This mode requires that all variables be explicitly declared before use. The default value, which is set in the <compilation> section of the machine.config configuration file, is True. Note that the documentation for the @ Page directive indicates that the default for this attribute is False (while also indicating that the value is set to True in machine.config). This may refer to the vbc.exe compiler having Option Explicit turned off by default. Since the explicit attribute in the <compilation> element of machine.config is set to True, however, the default for ASP.NET pages is effectively True.

Inherits
<%@ Page Src="path" Inherits="namespace.class" %>

Specifies the namespace (optional) and class name of a class from which the page will inherit. This attribute is used with the Src or Codebehind attribute to specify a code-behind file from which the page should inherit, thus making any properties and/or methods of that class available to the page.

Language
<%@ Page Language="languagealias" %>

Specifies the language that will be used for server-side <script> blocks and render blocks on the page. Typical values are VB (for Visual Basic .NET) and C#. You can also use the Language attribute of a server-side <script> tag to specify the desired language for individual <script> blocks. Unlike classic ASP, ASP.NET only supports one language per page.

LCID
<%@ Page LCID="localeidentifier" %>

Specifies the locale identifier (LCID) for the page. The locale identifier is used by functions such as the Visual Basic .NET FormatCurrency function to determine the desired format. For example, setting the LCID attribute to 1041 results in FormatCurrency returning values formatted as Japanese yen (¥).

ResponseEncoding
<%@ Page ResponseEncoding="encodingname" %>

Specifies the encoding to be used for the page response. This attribute can be set to any valid encoding supported by System.Text.Encoding. The default is Unicode (UTF-8).

Src
<%@ Page Src="path" Inherits="namespace.class" %>

Specifies the path to a code-behind class to compile dynamically. This attribute is used in conjunction with the Inherits attribute to specify a code-behind class for the page that will be compiled when the page is requested (unless a cached version of the compiled assembly for the page already exists). Unlike the Codebehind attribute, which is only used by Visual Studio .NET (and is ignored by the ASP.NET runtime), the class file specified by the Src attribute is compiled dynamically at runtime.

SmartNavigation
<%@ Page SmartNavigation="True|False" %>

Specifies whether ASP.NET's SmartNavigation feature is enabled. SmartNavigation, which is supported only by IE 5.x and later, uses IFrame elements to allow only portions of the page to be refreshed when an ASP. NET page containing a form is posted to the server. This can eliminate the flicker associated with page refresh, and also prevents multiple entries in the browser history from postbacks. The default value, which is set in the <pages> section of the machine.config configuration file, is False.

Strict
<%@ Page Strict="True|False" %>

Specifies whether pages written in Visual Basic .NET will be compiled using Option Strict mode. This mode does not permit any implicit data type conversion that would result in data loss (also known as narrowing conversions) and does not allow late binding. Option Strict also includes the restrictions of Option Explicit, so setting the Strict attribute to True also requires that all variables be explicitly declared before use. The default value, which is set in the <compilation> section of the machine.config configuration file, is False.

Trace
<%@ Page Trace="True|False" %>

Specifies whether the ASP.NET tracing feature is enabled for the page. Enabling tracing at the page level results in information about the current request—including request time, HTTP status code, cookie information, page control tree, and HTTP header information—being appended to the page output. Tracing can provide a great deal of information useful for debugging or understanding what is happening with a given page. For performance and security reasons, tracing should not be enabled for production applications. The default value, which is set in the <trace> section of the machine.config configuration file, is False.

TraceMode
<%@ Page TraceMode="tracemode" %>

Specifies the sort order of entries in the Trace Information section of the page trace. Valid values include SortByTime, which sorts entries in the order in which they are processed, and SortByCategory, which sorts entries based on the category assigned to the entry. Developers can write custom entries to the trace output using the Trace.Write method and assign categories to these entries. In the SortByCategory trace mode, all custom entries using the same category would appear together. The default value, which is set in the <trace> section of the machine.config configuration file, is SortByTime.

Transaction
<%@ Page Transaction="transactionmode" %>

Specifies the transaction mode of the page. Valid values are Disabled, NotSupported, Required, RequiresNew, and Supported. Default is Disabled.

UICulture
<%@ Page UICulture="culturename" %>

Specifies the culture that should be used when loading language-specific resources for pages that use resource files.

ValidateRequest
<%@ Page ValidateRequest="True|False" %>

Specifies whether request validation should be performed. Request validation, a new feature in ASP.NET v1.1, checks all posted input data for potentially dangerous values, such as HTML and script. If such input is found, an exception of type HttpRequestValidationException is thrown. The default value, which is set in the <pages> section of the machine.config configuration file, is True.

You should always leave Request Validation enabled, unless your application must accept HTML input. If this is the case, you should filter your input (using regular expressions or similar techniques) for the specific input you wish to allow (such as <b>, <i>, etc.) and disallow everything else. If instead you attempt to filter out invalid input, you are almost certain to miss some form of dangerous input, leaving your application vulnerable to exploit. Once you are confident that your filtering is working, you can disable Request Validation at the page level. While it's possible to disable Request Validation at the application and machine level, doing so exposes your application to higher risk, since this makes it too easy to add a new page that accepts input, forgetting to include filtering logic. Without Request Validation enabled, such a page could pose a security risk.

WarningLevel
<%@ Page WarningLevel="warninglevel" %>

Specifies the compiler warning level at which ASP.NET should abort compilation of the page and display the warning. The available values for this attribute depend on the language in use. See the documentation for the appropriate compiler for more information.

@ Control

Provides much the same functionality as the @ Page directive, only for ASP.NET user controls. The attributes available for the @ Control directive, which are a subset of those for the @ Page directive, include the following:

AutoEventWireup
ClassName
Codebehind (Visual Studio .NET only)
CompilerOptions
Debug
Description
EnableViewState
Explicit
Inherits
Language
Strict
Src
WarningLevel
@ Import

Allows access to members of a namespace without using the fully qualified (namespace and member name) name. The @ Import directive has a single attribute, Namespace, which specifies the namespace to import. Multiple @ Import directives must be used to import multiple namespaces, with one @ Import directive for each desired namespace.

@ Implements

Specifies an interface that the page or control implements in which the directive appears. By implementing an interface, the page developer agrees to provide implementations of all methods and/or properties defined by the interface. Failure to implement any of the members defined by the interface results in a compiler error. The @ Implements directive has a single attribute, Interface, that specifies the .NET interface to be implemented.

@ Register

Allows the instantiation and use of user controls and custom server controls in ASP.NET pages and user controls through an HTML-like tag-based syntax. The @ Register directive is used to specify the tag prefix (similar to the asp: prefix for built-in ASP.NET Server Controls) and the information necessary to locate the user control or custom server control. The @ Register directive supports the following attributes:

TagPrefix

Specifies the prefix to be used to differentiate the tag used to create an instance of the user control or custom server control.

TagName (user controls only)

Specifies the tag name (the portion of the tag immediately following the tag prefix, which is separated from the tag name by a colon) used to create an instance of a user control. For custom server controls, the class name of the class that defines the server control is used for the tag name, so this attribute is not necessary.

Namespace (custom server controls only)

Specifies the namespace of the custom server control.

Src (user controls only)

Specifies the path to the .ascx file containing the desired user control.

Assembly (custom server controls only)

Specifies the assembly containing the custom server control class.

A complete @ Register directive for a custom server control is:

<%@ Register TagPrefix="foo" Namespace="foo" Assembly="bar" %>

Assuming a class name of "baz" for the custom server control, the corresponding tag for an instance of the control is shown here:

<foo:baz id="myBaz" runat="server"/>

See Chapter 6 for additional examples.

@ Assembly

Specifies the name or path to an assembly to be linked in with the current page. This specification makes any classes or interfaces in the assembly available to the page. Note that the following assemblies are linked into pages by default based on the <assemblies> child element of the <compilation> element in the machine.config configuration file (see Chapter 8 and Chapter 20 for more information on configuration files):

mscorlib
System
System.Data
System.Drawing
System.EnterpriseServices
System.Web
System.Web.Services
System.Xml

Note that the <assemblies> element of machine.config also contains a wildcard reference (*) that tells it to link any assemblies residing in the bin subdirectory of the application. Any custom assemblies you place in this directory (including custom control assemblies) will be available to your application automatically. Unlike the @ Import directive, this directive does not make it possible to access members of an assembly without using the fully qualified name. The @ Import directive is still required for that. The @ Assembly directive supports two attributes, which are exclusive of one another:

Name

Specifies the name of the assembly to link. This is typically the same as the filename of the assembly, without the file extension (i.e., the assembly name for System.Web.dll would be System.Web).

Src

Specifies the path to a class module that is to be dynamically compiled and linked into the current page.

@ OutputCache

Enables and specifies settings for caching the output of ASP.NET pages or user controls. Caching can significantly improve the performance of ASP.NET applications. Output may be cached on the server, on the client, or on intermediate machines, depending on the value of the Location attribute. The @ OutputCache directive supports the following attributes:

Duration

Specifies the time in seconds for the output of the page to be cached. Note that for output cached by the ASP.NET cache engine on the server, cached output may be evicted from the cache before this duration has elapsed if the page is requested infrequently or if there is a shortage of available memory on the web server. This attribute is required.

Location (pages only)

Specifies where page output should be cached. Valid values include Any, Client, Downstream, None, or Server. The default is Any. This attribute is supported only for output caching with ASP.NET pages. Attempting to use this attribute for caching user controls results in a parser error.

VaryByCustom

Specifies a custom caching variation scheme. Setting the value to browser varies the cache based on the name and major version number of the client's browser. To use this attribute for any other custom value, you must override the GetVaryByCustomString method of the HttpApplication class in the global.asax file.

VaryByHeader (pages only)

Specifies a list of one or more HTTP headers, delimited by semicolons, to be used to vary the output cache. Requests with identical values for the specified headers will be served a cached version of the page (if one exists). If no matching page exists in the cache, the page is processed and the resulting output is cached. This attribute is supported only for output caching with ASP.NET pages. Attempting to use this attribute for caching user controls will result in a parser error.

VaryByParam

Specifies a list of one or more HTTP GET or POST parameters, delimited by semicolons, to be used to vary the output cache. Requests with identical values for the specified parameters will receive a cached version of the page (if one exists). If no matching page exists in the cache, the page is processed and the resulting output is cached. This attribute is required. To disable varying the cache by parameter, set the value to none. To vary by all parameters, set the value to the * wildcard.

VaryByControl (user controls only)

Specifies a list of one or more properties of a user control, delimited by semicolons, to be used to vary the output cache. Requests with identical values for the specified parameters will receive a cached version of the user control (if one exists). If no matching user control exists in the cache, the user control is processed and the resulting output is cached. This attribute is required unless a VaryByParam attribute has been specified for the user control's @ OutputCache directive.

@ Reference

Specifies the path to an ASP.NET page or user control that will be compiled dynamically and linked into the current page. The @ Reference directive supports the following attributes:

Page

Specifies the path to a page to be dynamically compiled and linked.

Control

Specifies the path to a user control to be dynamically compiled and linked.

3.1.2 Combining User Interface and Code

Although ASP.NET makes it possible to create much more complex, structured web applications, you can continue to use the simple coding style characteristic of ASP in which code and HTML are combined. This is illustrated in Example 3-1, a simple form that displays the message "Hello World" in the browser window.

Example 3-1. A simple Web Form (HelloWorld.aspx)
<%@ Page Language="VB" %>
<html>
<head>
<title>My First Web Form</title>
<script runat="server">
   Sub Page_Load(Sender As Object , e As EventArgs )
      Message.Text = "Hello World!"
   End Sub
</script>
</head>
<body>
   <form runat="server">
      <asp:Label id="Message" runat="server" />
   </form>
</body>
</html>

This Web Form uses a server control, <asp:Label>, to output the text "Hello World". The server control is declared using a tag with the prefix asp: followed by the attribute runat="server". The attribute runat="server" indicates that the code will run on the server and the output will be sent to the browser. The Label control is used to display static text and can be changed using the control's Text property. The entry point into the executable code in Example 3-1 is the event handler for the Page object's Load event, which is called automatically when the page loads.

The tag prefix asp: denotes the namespace. Namespaces define the scope of the controls. Namespaces allow the existence of multiple controls with the same name. Using namespaces, the .NET Framework classes are neatly grouped under hierarchies based on their functionality.

When the page is requested from the browser for the first time, it is compiled and cached. The compiled code is then used to generate the content dynamically. You may notice a delay when you request any ASP.NET page for the first time because of the compilation. Subsequent requests will execute much faster.

To understand how an ASP.NET page is rendered on the browser, you should look at the generated HTML content from within the browser, which is accessible by selecting Internet Explorer's View Source menu option. The generated HTML from Example 3-1 is shown in Example 3-2.

Example 3-2. Generated HTML from an ASP.NET page
<html>
<head>
<title>My First Web Form</title>
  
</head>
<body>
   <form name="_ctl0" method="post" action="HelloWorld.aspx" id="_ctl0">
<input type="hidden" name="_  _VIEWSTATE" 
value="dDw4MDE0NzI0MDA7dDw7bDxpPDI+Oz47bDx0PDtsPGk8MT47PjtsPHQ8cDxwPGw8VG 
V4dDs+O2w8SGVsbG8gV29ybGQhOz4+Oz47Oz47Pj47Pj47Pg==" />
  
      <span id="Message">Hello World!</span>
   </form>
</body>
</html>

As you can see by comparing Examples Example 3-1 and Example 3-2, the Label server control has been modified to become the HTML <span> tag. Also notice that a hidden form field stores the state of the Label server control.

3.1.3 Code-Behind Files

ASP.NET promotes the separation of code and content. The use of code-behind files is one of the mechanisms that aides the separation of the UI and the UI logic. Developing an ASP.NET page using code-behind files requires two steps:

  1. Developing the page's UI using HTML and web controls.

  2. Developing the UI logic (code-behind) using any of the .NET languages.

A code-behind file consists of a class inherited from the Page class. It provides an object-oriented way of developing the UI logic of an ASP.NET page. The code-behind file has member variables, event handlers, and helper methods that are called from the event handlers specific to an ASP. NET page. The ASP.NET page and the code-behind file are tightly coupled, meaning that changes in one usually often require the other to be changed in order for both to function correctly. Fortunately, when developing pages using code-behind in Visual Studio .NET, most of this is taken care of for you.

The extension of the code-behind file varies depending upon the .NET programming language you choose to develop the code. Typically, it will be .cs for C#, .vb for Visual Basic, or .js for JScript. You can decide to either precompile the code-behind file or let ASP.NET compile the code-behind file for you.

The Page directive provides the glue between an ASP.NET page and a code-behind file at the beginning of your ASP.NET page. The Inherits attribute of the Page directive specifies the name of the .NET class that encapsulates the UI logic. The Src or Codebehind attribute specifies the path to the filename that contains the .NET class itself. Use the Codebehind attribute if the code-behind file is precompiled; otherwise, use the Src attribute. Note that the Codebehind attribute is used only by Visual Studio .NET; it is ignored by the ASP.NET parser. By contrast, the ASP.NET parser uses the Src attribute to locate and compile the code-behind class.

One of the most commonly used pages in any web application is a sign-in page. Example 3-3 shows the HTML source for a simple ASP.NET sign-in page that uses a code-behind file. Note that this example is not designed to show a secure login procedure, but rather to demonstrate the use of code-behind with a Web Forms page. We'll look at creating a login page in Chapter 9. Also note that this example requires that either the page and code-behind class belong to a Visual Studio .NET project, which Visual Studio would need to build before the page is browsed, or the code-behind class be manually compiled and placed in the application's bin subdirectory before the page is browsed.

Example 3-3. ASP.NET page using a code-behind file (CodeBehind.aspx)
<%@ Page language="vb" Codebehind="Codebehind.vb" 
   Inherits="aspnetian.CodeBehind" %>
<html>
<head></head>
<body>
   <form runat="server">
      <h1>Code-behind demonstration</h1>
      <p>
         <asp:label id="Message" runat="server">
         Enter your name to sign in:
         </asp:label>         
      </p>
      <p>
         <table id="SignInTable" cellpadding="5"
            cellspacing="1" bgcolor="Silver" runat="server">
            <tr>
           <td align="right">Name:</td>
               <td align="left">
                  <asp:textbox id="SignInBox" width="200" runat="server"/ >
               </td>
            </tr>
            <tr>
               <td colspan="2" align="middle">
                  <asp:button id="SignInButton" runat="server" 
                     text="Sign in"/>
               </td>
            </tr>
         </table>
      </p>
   </form>
</body>
</html>

The first line of the page is a Page directive that has the Codebehind and Inherits attributes set to appropriate values. Note that when declaring server controls, we have the option of using both an opening and closing tag (as exemplified by the Message Label control) when the tags contain text to be applied to one of the control's properties (in this case, the Text property), or using a single tag with a closing slash (/). This follows the standard for XML/XHTML syntax.

The source code for the code-behind file is given in Example 3-4. If you look at the member variables of the code-behind class, they have a one-to-one mapping with the IDs of the controls in the ASP.NET page. This mapping is very important because these member variables are the programmatic accessors to the controls in the page. You should also note that they are declared as Protected, which means that they are accessible only within the code-behind class and the Web Form that inherits from the code-behind class.

Example 3-4. Code-behind file (CodeBehind.vb)
Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Namespace aspnetian
  
Public Class CodeBehind : Inherits System.Web.UI.Page
   Protected Message As Label 
   Protected SignInTable As HtmlTable 
   Protected WithEvents SignInButton As Button 
   Protected SignInBox As TextBox
  
   Protected Sub Page_Load(sender As Object, e As EventArgs)
      If Page.IsPostBack Then
         Message.Text = "Time is: " & DateTime.Now( ) & "<br />" & _
           Message.Text
      End If
   End Sub
  
   Protected Sub SignInButton_Click(obj As Object, e As EventArgs ) _
      Handles SignInButton.Click
      Message.Text = "Congratulations, " & SignInBox.Text & _
         "!!! You have successfully signed in."
      SignInTable.Visible = false
   End Sub
  
End Class
End Namespace

If you are using Visual Studio .NET to test the preceding example, you should note that Visual Studio automatically inserts the AutoEventWireUp attribute of the @ Page directive in each new .aspx file created with the IDE, and sets its value to False. If AutoEventWireUp is set to False, the Page_Load event handler shown in Example 3-4 will not fire. Fortunately, Visual Studio .NET also automatically adds a Handles clause (Handles Page.Load) to wire up the event handler automatically as well, so you shouldn't have to worry about it.

All code for the page has been removed from the Web Forms page into the code-behind class.

Because the Codebehind attribute is specified in the Page directive, the code-behind file needs to be compiled into a .dll file and deployed into the /bin folder of your application. Since the code-behind file shown in Example 3-4 uses Visual Basic, you will typically invoke the VB compiler with the options shown here:

vbc.exe /out:bin\Codebehind.dll /r:System.dll,System.web.dll /t:library Codebehind.vb

For convenience, it's usually a good idea to set up a DOS batch file (.bat extension) with the compilation instructions. Then you can double-click the batch file in Windows Explorer to recompile the code-behind class. Example 3-5 adds the pause command to allow you to view any warnings or errors returned by the compiler before the command-line window is closed.

Example 3-5. Batch compilation file (MakeCodebehind.bat)
vbc.exe /t:library /r:System.dll,System.web.dll /out:bin\Codebehind.dll Codebehind.vb 
  
pause

Because the .NET Framework SDK setup program does not register the path to the command-line compilers, the command in Example 3-5 will work only if you add the path to the compilers to the PATH environment variable. Otherwise, you will need to use the full path to vbc.exe in your batch file. To add the path to vbc.exe to the PATH environment variable, do the following:

  1. Right-click the My Computer icon on the desktop and select Properties from the menu.

  2. Select the Advanced tab and then click the Environment Variables... button.

  3. Under System Variables, scroll to the Path variable, select it, then click Edit...

  4. Add a semicolon, followed by the path to vbc.exe (typically %windir%\ Microsoft.NET\Framework\%version%\, replacing %windir% with the path to your Windows directory and %version% with the version number of the framework install you want to target) and click OK.

  5. Click OK on the Environment Variables and System Properties dialogs to close them. You may need to reboot for this change to take effect.

In Visual Studio .NET, the compilation of a code-behind class is taken care of automatically when you build the project containing the Web Form that uses it. This is tracked by the Codebehind attribute of the @ Page directive.

    [ Team LiB ] Previous Section Next Section