Sunteți pe pagina 1din 77

ASP.NET 4.

0 Web Pages
Learning Objectives
After completing this topic, you should be able to

recognize the steps for creating a basic web page distinguish between the single-file and code-behind page models

1. Creating a basic web page


Visual Studio 2010 helps you create web sites and web applications based on the ASP.NET 4.0 development model. Such applications and web sites can run in any type of browser and on any computer or mobile device. In addition, you can develop the applications and web sites using any language, such as Microsoft Visual C#, that the .NET common language runtime recognizes. Each ASP.NET 4.0 application and web site contains an .aspx web page by default. You can add more such web pages to your applications and web sites. The web pages act as the user interface for the applications and web sites. ASP.NET 4.0 includes three new templates one for an Empty Web Application project, one for a Web Application, and one for a Web Site project. Visual Studio 2010 provides Empty Web Applications and Empty Web Site projects that contain a minimal Web.config file, which contains information used by Visual Studio to identify the framework that the project is targeting. The Web Applications and Web Sites templates contain new project layouts as well as a number of files that were not in earlier versions. The new project is configured with basic membership functionality, which allows you to begin securing access to the new application. This inclusion means that the Web.config file for a new project includes entries used to configure membership, roles, and profiles. The project's Account folder contains the web pages that you use to implement authentication. The pages created by default in a new project template contain more content than in previous versions. For instance, it includes a default master page and CSS file. Also, the default page is configured to use the master page by default so that the default page is already functional when you run the web application or web site for the first time. ASP.NET 4.0 web pages offer benefits that include

flexibility ASP.NET 4.0 web pages offer you the flexibility to run them on any type of computer or mobile device. simplicity The simplicity of ASP.NET 4.0 web pages lies in the ease with which you can manage the contents of pages. The ASP.NET page framework helps automate most management activities. Moreover, you don't require additional server resources or cookies to accomplish these activities. browser independence Browser independence is achieved because ASP.NET 4.0 renders web pages for a variety of browser types automatically. However, if you want to run the pages in a particular type of browser, you also have the option to use client-side code to tailor the page for a specific browser type. cohesiveness, and The ASP.NET page framework helps make each ASP.NET 4.0 web page a cohesive entity that is independent of its client-side and server-side code. Thus, you can incorporate features in the page without having to make complex changes in the code. an innovative programming model The ASP.NET 4.0 web pages offer you an innovative programming model. Using this model, you can include event handlers in both the client-side and the server-side code. Additionally, the model ensures you don't have to configure or monitor transactions taking place between the client or the server and the event handlers. You can include an assortment of inbuilt controls, such as the ListView control, in each ASP.NET 4.0 web page. You can also use third-party controls or create and use controls of your own. The controls help you to considerably increase the functionality and user-friendliness of your web site or application using a minimal amount of code. You can also run each newly created page to ascertain whether it is working properly. The web server built into Visual Studio 2010 helps you run the page. Suppose you want to demonstrate to your colleagues how a basic ASP.NET 4.0 web page is created and run using Visual Studio 2010. You open the application by selecting Start Programs - Microsoft Visual Studio 2010 - Microsoft Visual Studio 2010.

Note
Alternatively, if a Microsoft Visual Studio 2010 icon appears on your desktop, you can doubleclick the icon to open Visual Studio.

Try It
Visual Studio 2010 is now open. To create an ASP.NET 4.0 web page in Visual Studio 2010, you first have to create a new web site using an appropriate template.

The Visual Studio 2010 Start Page is open and a Toolbox, standard menu bar and toolbar are also displayed. The Start Page includes links to connect to a team foundation server, create new projects, open existing projects, or view recently opened web sites. The Start Page also includes three tabbed sections - Latest News, Get Started, and Guidance and Resources. To complete the task 1. Select File - New Web Site Using keyboard: The keyboard alternative is Alt+F, W. Another keyboard alternative is Shift+Alt+N. The New Web Site dialog box opens. The New Web Site dialog box lists templates you can use to create your web site. The ASP.NET Web Site template is selected by default. Because you want to create an ASP.NET web page, you retain the default selection.

Graphic
The Templates section in the New Web Site dialog box is divided into three subsections - recent templates, installed templates, and online templates. The second subsection, Visual Studio installed templates, is expanded by default and lists the templates available on your hard disk, which include Visual Basic and Visual C#. Visual Basic is selected by default. The third section lets you search online templates.

Note
You can also choose File - New Project and select ASP.NET Web Application to create a web application project. This creates a project file, .vbproj, that acts as a container for the application files in contrast to the web site structure which is simply a windows folder. The web site structure provides greater flexibility and ease of use while the web application project provides greater control over compilation and execution for development teams. You retain the default location, File System, as well. However, you change the name of the web site from WebSite2 to BasicWeb1 by editing the default path.

Graphic
In the dialog box, the Web location drop-down list currently displays File System selected, and the adjacent drop-down list displays the default path for the web site. You can use the Browse button to change the location. You can click OK to continue.

Visual Studio 2010 opens the new web site, BasicWeb1, in a window displaying the Default.aspx web page that is automatically created.

Graphic
The new web site contains an active page and the Toolbox pane. The Toolbox pane in Visual Studio 2010 includes controls you can add to the currently active page in this case Default.aspx of your web site.

Graphic
The Toolbox pane displays a section named Standard. This section is expanded and displays controls such as Pointer, Label, TextBox, Button, LinkButton, and ImageButton.

Note
If the Toolbox pane isn't visible, you can open it by selecting View - Toolbox. The keyboard alternative is Ctrl+Alt+X. The Solution Explorer pane helps you view the structure of your web site. In this example structure, a folder named BasicWeb1 includes a subfolder named App_Data, a Default.aspx web page, and a Web.config file.

Graphic
The Solution Explorer pane uses a tree view to represent the structure of your web site.

Note
If the Solution Explorer pane isn't visible, you can open it by selecting View - Solution Explorer. The keyboard alternative is Ctrl+Alt+L. Using the Properties Window, you can set the properties of the controls you add to the Default.aspx page. Fields representing the properties of a control become visible in the Properties Window as soon as you select the control in the Default.aspx page. You can assign appropriate values to each field. For example, you can change the text, Label, that appears by default in a Label control by editing the control's Text field.

Graphic

In the example, the code for a Label control named Label1 appears in the Default.aspx page. The code is selected. The Properties Window displays two fields ForeColor, and Text related to Label1. The value in the Text field reads Label, and the ForeColor field is blank.

Note
If the Properties Window is not visible, you open it by selecting View - Properties Window. The keyboard alternative is F4. Visual Studio 2010 displays the contents of the Default.aspx page in the Source view by default. This view allows you to examine and edit the source code of the page per your requirements.

Code
<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content>

The code in the Default.aspx page is primarily made of HTML tags such as

Code
<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2>

Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content> <html> <head> <body> <form> <div>

The code also contains a few non-HTML items.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content> @ Page

The @ Page command is a directive that helps you use attributes such as Language in an .aspx page. These attributes guide ASP.NET on how to compile the .aspx page. Aside from the @ Page directive, which can be used only in .aspx pages, ASP.NET provides other directives such as @ Master. The @ Master directive can be used only in a .master file and helps ASP.NET compile the file correctly. Each directive and its attributes are enclosed within <% and %> tags.
Language

Using the Language attribute, you can indicate to a web browser that your ASP.NET page includes script elements written in a particular language. In the example, the value of the Language attribute indicates that the Default.aspx page contains Visual Basic code.
AutoEventWireup

You can use the AutoEventWireup attribute to automatically associate page events with event handlers.
CodeFile

If you want an external file to contain the script elements in your page, you can specify the name of the file in this case, Default.aspx.vb using the CodeFile attribute.
Inherits

If you specify an external file for your page, you should use the Inherits attribute to indicate the class that the code in the file will inherit. Normally, the class has the same name as the external file. Another important part of the code in the Default.aspx page is the runat="server" attribute.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content>

If you want the contents of any HTML element in the code to be interpreted by the server rather than by a web browser, you place the runat="server" attribute in the opening tag of that element.

Graphic
In the example, the runat="server" code is used as an attribute in the opening head and form tags.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <h2> Welcome to ASP.NET! </h2> <p> To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>. </p> <p> You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409" title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>. </p> </asp:Content>

An advantage of using Visual Studio 2010 is that it also allows you to open and edit web pages using views other than the Source view. Design The Design view displays the output of the source code for your web page. It provides a visual layout of how the web page will look. You can directly drag and drop controls and components onto the page in this view. The Design view for a newly created web page appears blank because the page does not contain any controls. Split Using the Split view, you can simultaneously examine both the code in the Source view and the design layout in the Design view of your web page. You can also edit the code in

the Source view and observe the changes being replicated in real time in the Design view and vice versa.

SkillCheck
You want to create a basic ASP.NET 4.0 web site with a blank web form. So you open Visual Studio 2010. Use appropriate menu options to create the page. Save the page keeping the default name provided by Visual Studio 2010. The Visual Studio 2010 Start Page is open. Task: 1. Open the New Web Site dialog box. 2. Select the template that will help you create the desired web page and close the New Web Site dialog box.

Answer
To complete the task Step 1: Select File - New Web Site Using keyboard: The keyboard alternative is Alt+F, W. Another keyboard alternative is Shift+Alt+N. Step 2: Ensure that ASP.NET Web Site is selected as the template, retain the default name of the web site, and click OK

2. Adding controls to web pages


In previous versions of Visual Basic, a blank web form was added to a new web page by default. Visual Studio 2010 provides options to add several items to your web site.

Graphic
The newly created BasicWeb1 web site is open and Default.aspx page is open in the active pane. The Toolbox and Solution Explorer panes are also open. To add a web form, you right-click the site or project name in Solution Explorer. You then select Add New Item from the shortcut menu.

Keyboard Sequence
The keyboard sequence to add a new time is Ctrl+Shift+A. The Add New Item dialog box opens, displaying a list of items you can add to your web page. Web form is selected by default.

Graphic
The Add New Item dialog box displays templates installed on your computer such as Web Form, Browser File, and AJAX Client Behavior-enabled WCF Service. There are two checkboxes named Place code in separate file and Select master page in this dialog box. The former is selected by default. You clear the Place code in separate file checkbox and click Add. The BasicWeb1 web site now contains a web form page named Default2.aspx.

Note
A DOCTYPE declaration is automatically included in the page which by default specifies XHTML 1.0 Transitional, but you can change this if required. The Design view of a new web form is always blank. You can customize the web form by adding controls to suit your requirements. Suppose you want the web form, Page1.aspx, in the WebSite9 web site to include a text box, a button, or similar controls. You can add these controls by double-clicking them in the Toolbox pane of Visual Studio 2010.

Note
You can also drag and drop the control directly onto the page. In the Source view, you'll notice the code contains a nested <form> and <div> tag pair. The <form> tag pair creates the blank form in the page.

Graphic
The opening <form> tag also contains the attributes id="form1" and runat="server".

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Page1.aspx.vb" Inherits="_Page1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>

You can add controls in the Source view as well by directly inserting the code for the controls within the <div> tag pair.

Graphic
The <form> tag pair encloses the <div> tag pair.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Page1.aspx.vb" Inherits="_Page1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> </div> </form> </body> </html>

Try It
You decide to add a text box to the form using the Design view. The WebSite9 web site page, Page1.aspx, is open in Source view. To complete the task

1. Click the Design button The form opens in the Design view. You double-click TextBox in the Toolbox pane. This adds a text box to the blank form. To check whether the source code for the form has changed to reflect the addition of the control, you click the Source button to return to Source view.

Graphic
In the Source view, the line of code that represents the text box is <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>. This line of code appears between the <div> tags.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Page1.aspx.vb" Inherits="_Page1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"><asp:TextBox> </div> </form> </body> </html>

Notice the code that defines the TextBox control includes asp tags. These tags identify nonHTML code that must be interpreted and run by the server. The asp prefix helps the server locate the control it refers to, such as the TextBox control in this example. You now decide to add a button to the form. But before doing so, you need to edit the source code to ensure the button is properly separated from the text box you just added.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </div> </form> </body> </html>

To separate the existing TextBox control from the proposed button, you place two <br /> tags immediately after the code for the control.

Graphic
In the example, the two <br /> tags are highlighted.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /><br /> </div> </form> </body> </html>

You can place a Button control in the blank space immediately below the <br /> tags either by using the Toolbox pane or by typing the code for the control.

Code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /><br /> </div> </form> </body> </html>

Try It
You decide to add a Button control by typing the relevant code. To complete the task 1. Type <asp:Button ID="Button1" runat="server" Text="Button" /> and click the Submit button provided Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /><br /> INSERT THE MISSING CODE </div> </form> </body> </html>

A Button control has been added to the form.

Outcome
The completed code is: Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br /><br /> <asp:Button ID="Button1" runat="server" Text="Button" /> </div> </form> </body> </html>

You create another basic ASP.NET 4.0 web site, NewWeb, using Visual Studio 2010. The Default.aspx page for the web site is currently open in the Source view. You want to add a Label control to the blank form on the Default.aspx page. So you place the cursor within the <div> tags of the blank form.

SkillCheck
Type the code for the Label control at the cursor position. Task: 1. Type the code for the Label control at the cursor position and click the Submit button provided. Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> INSERT THE MISSING CODE </div> </form> </body> </html>

Answer
To complete the task Step 1: Type <asp:Label ID="Label1" runat="server" Text="Label" /> and click the Submit button provided

Outcome
The completed code is: Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label" /> </div> </form> </body> </html>

After adding controls to the form on a web page, you can easily modify the properties of the controls. For example, if you have added a button and a text box to a form, you can modify the name of the button and insert text in the text box.

Graphic
The Default.aspx page for the WebSite9 web site is open in the Design view.

Suppose you want to insert text in the text box that you added to the Page1.aspx page for the WebSite9 web site. You begin by selecting the text box. This displays the properties for the text box in the Properties Window. You can type the value for each property directly in the Properties Window.

Graphic
The Properties window for the text box displays the ForeColor and Text properties. Adjacent to each property is a text box in which you can type a value for the property. You want the text box to be labeled "Name" so you type Name in the text field and press Enter. The text box now displays the text Name. The code for the text box also gets added instantaneously to the source code for the Page1.aspx page. You can verify this by going to either the Source view or the Split view. In the example, the Page1.aspx page is open in the Split view, and the source section of the Split view displays the code for the text box with the text "Name."

Graphic
The code for the text box is <asp:TextBox ID="TextBox1" runat="server">Name<asp:TextBox>

Try It
You now want to change the color of the inserted text to blue and add a 2-pixel border to the text box. You change the text box by typing the values in the appropriate fields of the Properties Window. To complete the task 1. Type Blue in the ForeColor field, and click Enter 2. Type 2 in the BorderWidth field, and click Enter The font color of the text in the text box is changed and a 2-pixel border is added to it. After adding controls to your page, you can immediately run the page and test whether the page and its controls are working properly. To run the page, you select Debug - Start Without Debugging.

Keyboard Sequence
The keyboard alternative is Alt+D, H. You can also press Ctrl+F5 to run the page.

This opens the page in your default web browser. After confirming the page is as you want it to be, you can close it and also close Visual Studio 2010.

Question
You want to create an ASP.NET 4.0 web page that includes a text box named UserName, where users can type their name, and a button labeled Logon, which the users can then click to log on. Sequence the steps in the order you will perform them to create this web page using Visual Studio 2010. Options: 1. 2. 3. 4. Create a new ASP.NET web site Switch to the Design view Edit the Text properties of the TextBox and the Button control Double-click the TextBox and the Button control on the Toolbox pane

Answer
Correct answer(s): Create a new ASP.NET web site is ranked the first step. Visual Studio 2010 provides the ASP.NET Web Site template, which you can use to create an ASP.NET web site. To access the template, you open the New Web Site dialog box by selecting File - New Web Site. After making appropriate selections in the dialog box, you can create your web site. Switch to the Design view is ranked the second step. When you are in the Design view, you can add controls to a page by double-clicking the controls on the Toolbox pane or by dragging the controls from the Toolbox pane to the page. Double-click the TextBox and the Button control on the Toolbox pane is ranked the third step. Double-clicking the controls adds them at the cursor position on a page. You can reposition the controls to suit your requirements. Edit the Text properties of the TextBox and the Button control is ranked the fourth step. If you want a particular text string to appear in a control, you type the text string in the Text field in the Properties window for the control.

3. Identifying web page models


Each ASP.NET web page comprises a visual component and a code component. The visual component is the user interface of the page and the page elements displayed in the Design view of Visual Studio 2010. The code component, on the other hand, is the mechanism that helps load the page and enables the page to respond to events such as a button click.

To help you manage the visual and code components in a web page, Visual Studio 2010 offers two types of page models: the single-file and the code-behind model. The single-file model allows you to keep both the code and visual components of a web page in the same .aspx file. You use this model only if the code for your web applications and web sites is not lengthy and complex. The code components in the single-file model are enclosed within the <script> tag. The tag has the runat="server" attribute, which ensures the code components will be run from the server.

Graphic
In the example, the opening and closing <script> tags are highlighted. The opening script tag contains the attribute runat="server".

Code
<%@ Page Language="VB" %> <script runat="server"> Protected Sub TBox1_TextChanged(ByVal sender As Object, ByVal_ e As System.EventArgs) Handles TBox1.TextChanged Label1.Text = TBox1.Text Label1.ForeColor = Drawing.Color.Blue End Sub </script>

The visual components of the page appear within <html> tags.

Graphic
In the example, the opening and closing <html> tags are highlighted.

Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Single File Model</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TBox1" runat="server">Enter name</asp:TextBox> <br /><br /> <asp:Button ID="Button1" runat="server" Text="Submit" /> <br /><br /> <asp:Label ID="Label1" runat="server" Text="Waiting"></asp:Label> </div> </form>

</body> </html>

Notice the code in the single-file model doesn't contain any class definitions. During compilation, the code automatically derives from the System.Web.UI.Page class. By default, any web page in a web site that you create in Visual Studio 2010 is configured to use the code-behind model. However, adding a web page that uses the single-file model to the web site is simple.

Graphic
In the example, the first page of the EasyNomadOffice web site is open in the Source view. The Solution Explorer pane for the web site displays the structure of the web site. The structure indicates that C:\EasyNomadOffice is the root folder. The root folder contains a page named Default.aspx and a file named web.config. A file named Default.aspx.vb is nested below the Default.aspx page. Say you want to add a web page using the single-file model to the EasyNomadOffice web site. So you right-click the root folder, C:\EasyNomadOffice, in the Solution Explorer pane. Then you select Add New Item from the shortcut menu.

Graphic
The shortcut menu displays options such as Build Web Site, Publish Web Site, Add New Item, Add Existing Item, New Folder, and Add ASP.NET Folder. The Add New Item dialog box opens. The dialog box provides templates you can use to add various components to your web sites. The Web Form template, which is selected by default, helps you add a web page to a web site.

Try It
You want to use the Web Form template to create a web page using the single-file model. To complete the task 1. In the Add New Item dialog box, clear the Place code in separate file checkbox 2. Click Add The Solution Explorer pane indicates the EasyNomadOffice web site now contains two pages: Default.aspx and Default2.aspx. The Default2.aspx page is open in the Source view. A new web page, Default2.aspx, using the single-file model, is added to the EasyNomadOffice web site.

Unlike the single-file model, the code-behind model helps you separate the code components of your web page from its visual components by saving them in two separate file types. These are

Graphic
In the example, the icons representing Default.aspx and Default.aspx.vb are highlighted in the Solution Explorer pane for the EasyNomadOffice web site. the .vb file The .vb file contains the code that appears within the <script> tag in the single-file model. The code in the .vb file is declared using the Partial Class keyword. This keyword enables you to use only a part of a class definition in your web page. However, you can specify this class as Public as well. You also have the option to use C# and .cs files instead of .vb files. In the example, the icon representing Default.aspx.vb is highlighted. the .aspx file The .aspx file contains the visual components of your web page. The file uses the CodeFile attribute to point to the .vb file that contains the page's code components. In the example, the icon representing Default.aspx is highlighted. This code is typical for the .vb file of a web page using the code-behind model.

Code
Partial Class _Default Inherits System.Web.UI.Page Protected Sub TBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)_ Handles TBox1.TextChanged Label1.Text = TBox1.Text Label1.ForeColor = Drawing.Color.Blue End Sub End Class

In the example, the code in the .vb file is declared using a Partial Class named _Default. Also, note that the Inherits attribute is used to ensure the code derives from the System.Web.UI.Page class. That's because the code in a .vb file does not automatically derive from this class.

Graphic
In the example, the Partial Class declaration and the Inherits attribute are highlighted.

Code

Partial Class _Default Inherits System.Web.UI.Page Protected Sub TBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)_ Handles TBox1.TextChanged Label1.Text = TBox1.Text Label1.ForeColor = Drawing.Color.Blue End Sub End Class

The .aspx file for a web page contains this type of code.

Code
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Code Behind Model</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server">Enter text here</asp:TextBox> <br /><br /> <asp:Button ID="Button1" runat="server" Text="Click to set label" /> <br /><br /> <asp:Label ID="Label1" runat="server" Text="Label set to your input text"></asp:Label> </div> </form> </body> </html>

Unlike the code in an .aspx file using the single-file model, the code in this file doesn't contain the <script> tag. Also, the @ Page directive in the code includes the CodeFile attribute. The value for this attribute is set to the name of the .vb file in this case, Default.aspx.vb containing the code components for the web page.

Graphic
In the example, the CodeFile attribute is highlighted.

Code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Code Behind Model</title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server">Enter text here</asp:TextBox> <br /><br /> <asp:Button ID="Button1" runat="server" Text="Click to set label" /> <br /><br /> <asp:Label ID="Label1" runat="server" Text="Label set to your input text"></asp:Label> </div> </form> </body> </html>

If you want to create a simple web site or application containing only a few pages, you may use the single-file model. This will enable you to easily access and edit the code and visual components for each page. However, for a complex web site or application, the code-behind model is the better option. For example, if you want multiple web pages in a web site to use a common class, use of the codebehind model is more convenient. When you use this model, you do not need to write the code for the common class in each .aspx file. Instead, you save time and space by placing the code in a single .vb file and linking the file to all the .aspx files.

Question
You use various HTML and non-HTML elements when creating an ASP.NET web page. The elements you use depend on the type of page model you employ to create the web page. Match each element to the page model with which it is used. More than one element can match to a page model. Options: 1. 2. 3. 4. The CodeFile attribute A pair of <script> tags The Partial Class keyword The System.Web.UI.Page class

Targets: 1. Single-file page model 2. Code-behind page model

Answer
In an .aspx file based on the single-file page model, the <script> tags enclose code components. In the code-behind page model, the Partial Class keyword enables you to use only a part of a class definition in your web page. You place this keyword in a .vb file. In this file, you also use the Inherits attribute to ensure the code in the .vb file derives from the System.Web.UI.Page class. Then, in the associated .aspx file, you use the CodeFile attribute to point to the .vb file. Correct answer(s): Target 1 = Option B Target 2 = Option A, Option C, Option D

Summary
In Visual Studio 2010, you can easily create web sites and web pages using templates such as the ASP.NET Web Site template. You can also view and customize your web sites and pages using three views: Source, Design, and Split. The Source view presents the source code for your page, Design presents the output of the source code, and Split presents both the source code and its output at once. When designing ASP.NET web pages, you can choose between two design models. The singlefile page model incorporates all class definitions and script elements in the same file. The codebehind page model places the code and design elements for web pages in separate files. | Print | Contents | Close |

Creating Web Pages with ASP.NET 4.0


Learning Objectives
After completing this topic, you should be able to

create a basic ASP.NET web page using Visual Studio 2010 add and modify basic controls on a web page

Exercise overview
In this exercise, you're required to use Visual Studio 2010 to create an ASP.NET 4.0 web page containing a control. This involves the following tasks:

creating an ASP.NET 4.0 web page adding a web form adding a control, and modifying the control

You work for Quick24x7, a startup, as a web designer and developer. Yesterday, you attended a presentation on the useful features of ASP.NET 4.0. During the presentation, you also learned how Visual Studio 2010 helps simplify the process of creating web sites. You now want to demonstrate the ease with which a web page can be created in Visual Studio 2010 to your peers and colleagues at work.

Task 1: Creating an ASP.NET 4.0 web page


You want to begin your demonstration by creating a web page in Visual Studio 2010. So you open the Visual Studio 2010 application and are currently on the Start page of this application. Use the File menu to create a basic ASP.NET 4.0 web site. When creating the site, use the default location that Visual Studio 2010 provides. Steps list Instructions 1. Select File - New Web Site 2. Ensure that ASP.NET Web Site is selected as the default template and the default location is specified in the New Web Site dialog box, and then click OK

Task 2: Adding a web form


Add a web form to the site using Solution Explorer and ensuring that the code is not placed in a separate file. The shortcut menu is already open. Steps list Instructions 1. Select Add New Item 2. Clear the Place code in separate file checkbox and click Add 3. Click Add

Task 3: Adding a control


Now that you've created a basic ASP.NET 4.0 web page, you want to add a control to the blank web form in the page. The web page is open in the Source view. Use the Design view to add a HyperLink control to the web page. Steps list Instructions 1. Click the Design button 2. Double-click HyperLink in the Toolbox pane

Task 4: Modifying a control


Without switching to another view, modify the properties of the selected HyperLink control so it displays the text "Home" and its ForeColor is red. You've deleted the default name, Hyperlink, from the Text field. Steps list Instructions 1. Type Home in the Text field and press Enter 2. Type red in the ForeColor field and press Enter Visual Studio 2010 has been used to create a basic ASP.NET 4.0 web page and add a basic control, as well as modify the Text and ForeColor properties of the control. | Print | Contents | Close |

Managing States
Learning Objectives
After completing this topic, you should be able to

identify the benefits of client-side and server-side state management identify the steps for maintaining web site user information with profile properties

1. State management in ASP.NET


Web pages are stateless due to the nature of HTTP communication. Each new page request is unaware of the page requests that preceded it. For example, when you fill a web form split across

two pages, values entered in the first page are lost when you submit values of the second page to the web server. To overcome this limitation, ASP.NET offers state management options for storing and managing state information when a web page is posted back to the server. ASP.NET provides both client-side and server-side options to store and manage state information for a page or for the entire application. Client-side options store state information in the page or on the client computer whereas serverside options store information in the memory on the server. Client-side options provide better scalability because state information is stored in the user's browser. This helps improve server performance because browsers preserve states even when users are redirected to another server. However, client-side options offer minimal security for sensitive data. These options also consume more bandwidth because data is repeatedly passed between the client and the server. High bandwidth usage may slow down your application and impact its performance. On the other hand, server-side options are more secure because the state of a page is saved on the server and is not delivered to the client. This also reduces bandwidth usage and web page size. However, storing large amounts of information on the server uses server resources. This might lead to reduced server scalability and performance. Your decision on how and where to manage state information should be based on

the amount and type of information to be stored available server resources the level of security required for the information bandwidth used performance standards for your application specifications of targeted browsers the duration for which the information needs to be stored, and whether your application is served by a single process, a web farm, or a web garden application

Question

Mike has decided to preserve states using server-side options. What advantages can he expect? Options: 1. 2. 3. 4. Security for highly sensitive state data Better server performance Low bandwidth costs Maximum server performance

Answer
Option 1: Correct. Server-side options provide higher security than client-side options. Option 2: Incorrect. Server-side options store state data on the server. This can lead to reduced server scalability and performance. Option 3: Correct. Server-side options reduce bandwidth usage and web page size because state data is saved on a server instead of being sent to a browser. Option 4: Incorrect. Server-side options decrease server performance because they store large amount of data on the server. Correct answer(s): 1. Security for highly sensitive state data 3. Low bandwidth costs

2. Benefits and uses of state management


ASP.NET provides five options to manage state on the client side:
ViewState

The ViewState property is the default method that ASP.NET uses for web forms to preserve states of multiple requests of the same page. It encodes control values in Base64 and stores them in a hidden field called __ViewState. Values of the ViewState property are bound to controls. This enables controls to retain their values between post backs. The server accesses the encoded values after the page's PreInit event and before its PreRender event.
ControlState

You use the ControlState option to retain values of complex controls. For example, if a custom control has several checkboxes, the control should know the state of each checkbox when the page is posted back. You can also use ControlState to retain the values of a control when ViewState is turned off for a page or the application. This option also uses hidden fields to save values. hidden fields

You can use hidden fields to store page-specific information directly on a page. Values stored in a hidden field are not displayed in the browser. cookies, and Cookies are small text files on the client computer that help an application manage state by remembering users and their preferences. When a user first accesses an application, the application sends a cookie along with the requested page. When the user accesses the application again, the browser sends the cookie to help the application retrieve different types of information. For example, cookies can be used to retrieve user login or web usage details. query strings Query strings help preserve page state by attaching page data at the end of the URL. For example, a typical query string looks like this. An example of a typical query string is http://www.brocadero.com/search.aspx?keyword=baseball
ViewState is enabled by default for web forms. You can disable it at the page level the EnableViewState value from true to false in the <%@ Page %> directive.

by changing

Code
<%@ Page EnableViewState="false" Language="vb" _ Codebehind="Form.aspx.vb" Inherits="WebApplication.Form"%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> <p> <asp:Label ID="Label1" runat="server" style="font-weight: 700" Text="Birthday: "></asp:Label> </p> <p> <asp:TextBox ID="textBirthday" runat="server"></asp:TextBox> </p> <p> <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text=" Age: "></asp:Label> </p> <p>

Similarly, you can also enable or disable ViewState at the control level by setting a control's EnableViewState property to true or false.

Code
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> </div> <p> <asp:Label ID="Label1" runat="server" style="font-weight: 700" Text="Birthday: "></asp:Label> </p> <p> <asp:TextBox EnableViewState="true" ID="textBirthday" runat="server"></asp:TextBox> </p> <p> <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text=" Age: "></asp:Label> </p> <p>

You can also enable or disable ViewState for all pages in an entire application by using the enableViewState property in the <pages> subtag under the <system.web> tag. In this example, ViewState is enabled for all pages in the application.

Code
<configuration> <system.web> <pages enableViewState="true" /> </system.web> </configuration>

To implement ControlState, you override the OnInit, LoadControlState, and SaveControlState methods of the control. Say you want to enable ControlState for a control that saves an integer as state information. You begin by overriding the OnInit method of the control.

Graphic
The code you use to override the OnInit method is Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

Code

Inherits WebControl Dim currentIndex As Integer Dim postCount As Integer <Bindable(True), Category("Appearance"), DefaultValue(""), Localizable(True)> Property Text() As String Get Dim s As String = CStr(ViewState("Text")) If s Is Nothing Then Return "[" + Me.ID + "]" Else Return s End If End Get Set(ByVal Value As String) ViewState("Text") = Value End Set End Property Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter) output.Write(Text) End Sub Protected Overrides Sub OnInit(ByVal e As System.EventArgs)

Try It
You then call the Page.RegisterRequiresControlState method with the instance of the control to register Me in this example. To complete the task 1. Type Page.RegisterRequiresControlState (Me) and click the Submit button provided Code:
Protected Overrides Sub OnInit(ByVal e As System.EventArgs) INSERT THE MISSING CODE CurrentIndex = 0 MyBase.OnInit(e) End Sub

The Page.RegisterRequiresControlState method with the instance of the control to register is called.

Outcome
The completed code is:

Code:
Protected Overrides Sub OnInit(ByVal e As System.EventArgs) Page.RegisterRequiresControlState(Me) CurrentIndex = 0 MyBase.OnInit(e) End Sub

You then override LoadControlState and SaveControlState to save the required state information.

Graphic
The code you use to override LoadControlState and SaveControlState is Protected Overrides Sub LoadControlState(ByVal savedState As Object) Dim state As Integer = CType(savedState, Integer) Me.postCount = state MyBase.LoadControlState(savedState) End Sub Protected Overrides Function SaveControlState() As Object Return postCount End Function

Code
Set(ByVal Value As String) ViewState("Text") = Value End Set End Property Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter) output.Write(Text) End Sub Protected Overrides Sub OnInit(ByVal e As System.EventArgs) Page.RegisterRequiresControlState(Me) currentIndex = 0 MyBase.OnInit(e) End Sub Protected Overrides Sub LoadControlState(ByVal savedState As Object) Dim state As Integer = CType(savedState, Integer) Me.postCount = state MyBase.LoadControlState(savedState) End Sub

Protected Overrides Function SaveControlState() As Object Return postCount End Function

You can use hidden fields to store page-specific information directly on a page. Values stored in a hidden field are not displayed on a browser. Say you want to create a hidden field that calculates how many times a button is clicked on a web form. Using the Toolbox section, you first drag and drop a hidden field on the web form. Then in the web form's vb file, you enter the code that enables the hidden field to calculate the number of times the Click Me button is clicked.

Code
Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) 'The hidden field is used to store the number of times the button is clicked If (HiddenField1.Value = Nothing) Then HiddenField1.Value = "0" End If 'Increment the hidden field value by 1 HiddenField1.Value = Convert.ToInt32(HiddenField1.Value) + 1 Label1.Text = HiddenField1.Value End Sub

Cookies are managed by the browser. It receives cookies through the HTTPResponse class. To send a cookie to the browser you need to add it to the collection of cookies exposed by HTTPResponse. To create a cookie, you use the Response.Cookies property and specify a name and value for the cookie in the HTML script. You can set a cookie's date and time of expiration. You then add the cookie to the cookies collection. This example adds a cookie named userName to the cookies collection. This cookie expires a day after it is created.

Code
<% Response.Cookies("userName").Value = "David" Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)

%>

To read a cookie value from the client you use the Request.Cookies property.

Code
<% uname=Request.Cookies("username")response.write("username=" & uname)%>

Try It
Alternatively, you can also add a cookie to a cookie collection by creating an instance of an HTTPCookie object, setting its properties, and then using the Add method to add the cookie to the collection. Say you want to add a cookie named userName to the cookies collection that expires two days after it was created. The existing code is: Dim myCookie As MISSING CODE("userName") myCookie.Value = Richard myCookie.Expires = DateTime.Now.AddDays(2) Response.Cookies.Add(myCookie) To complete the task 1. Type New HttpCookie and click the Submit button provided Type New HttpCookie in the MISSING CODE field. The Courseware Player cannot recognize input from you keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key. Code:
Dim myCookie As INSERT THE MISSING CODE("userName") myCookie.Value = Richard myCookie.Expires = DateTime.Now.AddDays(2) Response.Cookies.Add(myCookie)

A cookie named myCookie is added to the cookies collection.

Outcome
The completed code is: Code:
Dim myCookie As New HttpCookie("userName") myCookie.Value = Richard myCookie.Expires = DateTime.Now.AddDays(2) Response.Cookies.Add(myCookie)

You use query strings to save a page state when copying and pasting a URL.

Graphic
In this example, the URL displayed is http://www.easynomadtravel.com.

Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' Obtains value from the query string, clckStr Dim queryClksNum As Integer If Not (Request.QueryString("clckStr") Is Nothing) Then queryClksNum = Integer.Parse(Request.QueryString("clckStr ")) + 1 Else queryClksNum = 1 End If ' Specify the query string in the hyperlink Url1.NavigateUrl += "? clckStr =" + queryClksNum.ToString Label1.Text = "Query clicks: " + queryClksNum.ToString End Sub

Query strings are appended to the end of a URL. After the URL, a question mark is appended, which is followed by every parameter that you want to hold in the query string. The parameters declare the parameter name followed by the equal to (=) symbol, which is then followed by the data to hold. Every parameter is separated with the ampersand symbol.

Graphic
The example shows this URL with a query string appended to it. http://easynomadtravel.com?username=Mike&city=Austin

Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ' Obtains value from the query string, clckStr Dim queryClksNum As Integer If Not (Request.QueryString("clckStr") Is Nothing) Then queryClksNum = Integer.Parse(Request.QueryString("clckStr ")) + 1 Else queryClksNum = 1 End If ' Specify the query string in the hyperlink Url1.NavigateUrl += "? clckStr =" + queryClksNum.ToString

Label1.Text = "Query clicks: " + queryClksNum.ToString End Sub

Note
You must always use the HttpUtility.UrlEncode method on data strings if you are displaying them directly. Each client-side state management option has its benefits and limitations:
ViewState ViewState

retains page and control states automatically and is secure because values are hashed, compressed, and encoded. However, storing large values can affect browser performance because page state is stored on the page. Also, ViewState can be turned off at the page level and its encoded values can be accessed easily by malicious users.

ControlState ControlState

is reliable for page-scoped and control specific data. You can customize how and where state data is written.

However, a certain amount of programming is required to save and load ControlState. hidden fields Hidden fields are supported by every browser and client device. However, because a hidden field can be tampered with and is stored in the page itself, it is not an appropriate option for sensitive or large amounts of data. cookies, and You can configure cookies with expiration rules, and you can have both temporary and persistent cookies. However, browsers can reject or limit the number of cookies they accept. For example, most browsers support only cookies of up to 4096 bytes. Cookies can also be tampered with, making them inappropriate for storing sensitive data. query strings Query strings are supported by all browsers and client devices, and they enable the exchange of information by directly modifying the URL. However, query strings pose security risks because their information is visible and can be easily modified in the browser. As a result, you can store limited information using query strings. To manage states on the server side, you have three options: application state You can save page data between posts to the server using application state, which is a key/value dictionary created with each URL request. It is an instance of the

class and can be used by all pages in a web application. You can use application state to store small amounts of frequently used data that doesn't change from one user to another. session state, and Session state works like application state; it is a key/value dictionary used for storing information. However, it works with the browser session for each user, so that each user has a separate session state. If the same user accesses your application again, the second session has a fresh session state. Session state is available to the client and is lost once the session expires. It is an instance of the HttpSessionState class. profile properties Profile properties allow you to create, store, and manage user-specific information without using a database. It is similar to session state, but it does not lose profile data when a session expires. This enables you to permanently store the options chosen by your users. You can use application state information directly by adding, accessing, or removing values from the Contents collection of the HttpApplicationState class. You can use this class anytime during an application's lifecycle to load the application state. For example, to use it when the application starts, you enter the code that loads the application state in the Application_Start method of the Global.asax file. Alternatively, you can also add the objects you want to load to the Static objects collection using the <object runat="server"> code in the Global.asax file.

HttpApplicationState

Graphic
For example, you can use this code in the Global.asax file: <object runat="server" scope="application" ID="MyData01" PROGID="MSWC.MYDATA01"> </object> You can enable the use of session state information by using the sessionState element of the <system.web> tag in the web.config file. In this example, the sessionState element configures an application for StateServer session mode. A session is identified using the SessionID property, which is stored in a cookie by default. You can also create cookieless sessions by setting the cookieless element as true. To turn off session state, you set the sessionState value to Off.

Code
<sessionState mode="StateServer"

cookieless="false" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString= "data source=127.0.0.1;user id=sa;password=" timeout="20"/>

To access session variable values, you use the Session property of the HttpContext object. This example creates and sets session variables for the name and company of a user.

Code
Session("UserName") = "Mike Hatfield" Session("Company") = "Gleeson Associates"

Each server-side state management option has its benefits and limitations: application state Application state is easy to implement, maintains only a single copy of the information for the entire application, and can be shared among all users. However, inadequate server resources affect performance. Also, state data is lost when you experience server problems. session state, and Session state is easy to implement, works with browsers that don't support cookies, can be customized and extended, and enables your applications to raise session-specific events. It can be used in web-garden or web-farm scenarios. However, data can easily be tampered with, particularly when implemented without using cookies. Variables that are modified or contain large datasets affect server performance. profile properties Profile properties enable you to manage user information without creating and maintaining a database. Also, the ASP.NET profile feature makes user information available using an API that can be accessed from anywhere in your application. This option requires a lot of configuration and slows performance because data is stored in a data store instead of server memory. It requires data maintenance to update persistent data.

Question
Bruce has created a search engine. He wants to save search queries entered by users using the URL. Which state management option enables him to do this? Options: 1. ControlState 2. Query strings

3. Cookies 4. ViewState

Answer
Option 1: Incorrect. ControlState stores state information in a hidden field and not in the URL. Option 2: Correct. Query strings preserve state information by attaching page data at the end of the URL. Option 3: Incorrect. Cookies store state information in text files and not the URL. Option 4: Incorrect. ViewState stores state information in a hidden field and not in the URL. Correct answer(s): 2. Query strings

Question
Match the given ASP.NET state management options with the way in which they are used. Options: 1. 2. 3. 4. Cookies
ViewState

Session state
ControlState

Targets: 1. It's enabled by editing the <system.web> tag in the web.config file 2. Used by overriding a control's OnInit method 3. Stores small text files in the client's computer to remember preferences and lets you specify expiration rules 4. Encodes control values in Base64 and stores them in a hidden field

Answer
You can enable session state by using the sessionState element of the <system.web> tag in the web.config file. You implement ControlState by overriding a control's OnInit, SaveControlState, and LoadControlState methods.

Cookies are small text files on the client computer that help an application manage state by remembering users and their preferences.
ViewState encodes __ViewState.

control values in Base64 and stores them in a hidden field called

Correct answer(s): Target 1 = Option C Target 2 = Option D Target 3 = Option A Target 4 = Option B

3. Using profile properties


Profile properties enable you to permanently store user-specific data in your web application. For example, a user can specify a city name or language preference, and your application can retrieve this information every time the user visits your web site. Say you have created a web form that provides data according to a user's birth date and age. You want to use profile properties to ensure your application permanently stores values entered by your users. To add profile properties, you begin by adding the <profile> attribute under the <system.web> attribute in the web.config file.

Code
<system.web> <profile>

<compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral,

PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <pages> <namespaces>

Under the <profile> attribute, you use the <properties> attribute to define all profile properties. In this example, you have defined profile properties for the Birthday and Age fields. Also, you have set the data type for both properties as String. You can also indicate the data type for a property as Integer, DateTime, or StringCollection.

Graphic
In this example, you enter this code to define profile properties: <properties> <add name="Birthday" type="System.String" /> <add name="Age" type="System.String" /> </properties> </profile>

Code
<system.web> <profile> <properties> <add name="Birthday" type="System.String" /> <add name="Age" type="System.String" /> </properties> </profile> <compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <pages> <namespaces>

You then use the anonymousIdentification attribute to specify whether or not you want to enable profile properties for anonymous users. Anonymous users are unauthenticated users that have not logged in. Setting this attribute's enabled value to true enables profile properties for anonymous users and setting its enabled value to false disables profile properties for anonymous users.

Code
<system.web> <profile> <properties> <add name="Birthday" type="System.String" /> <add name="Age" type="System.String" /> </properties> </profile> <anonymousIdentification enabled=

/>

<compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <pages> <namespaces>

Try It

You want to enable profile properties for anonymous users to increase traffic to your web site. To complete the task 1. Type "true" and click the Submit button provided The Courseware Player cannot recognize input from you keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key. Code:
<system.web> <profile> <properties> <add name="Birthday" type="System.String" allowAnonymous="true" /> <add name="Age" type="System.String" allowAnonymous="true" /> </properties> </profile> <anonymousIdentifcation enabled=INSERT THE MISSING CODE/> <compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, PublicKeyToken=B77A5C561934E089" /> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly="system.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <assemblies> </compilation> <pages> <namespaces>

Profile properties are enabled for anonymous users.

Outcome
The completed code is: Code:
<system.web> <profile> <properties> <add name="Birthday" type="System.String" allowAnonymous="true" /> <add name="Age" type="System.String" allowAnonymous="true" /> </properties>

</profile> <anonymousIdentifcation enabled="true"/> <compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, PublicKeyToken=B77A5C561934E089" /> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <add assembly="system.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /> <assemblies> </compilation> <pages> <namespaces>

The anonymousIdentification property enables or disables all profile properties for anonymous users. However, you may sometimes want some profile properties enabled and some profile properties disabled for anonymous users. In such situations, you use the allowAnonymous attribute under each profile property. In this example, you have enabled the profile property of the Birthday field and disabled the profile property of the Age field for anonymous users.

Code
<system.web> <profile> <properties> <add name="Birthday" type="System.String" allowAnonymous="true" /> <add name="Age" type="System.String" allowAnonymous="false" /> </properties> </profile> <anonymousIdentification enabled="true"/> <compilation debug="false" strict="false" explicit="true"> <assemblies> <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies>

</compilation> <pages> <namespaces>

After editing the web.config file, you edit the .vb file of the .aspx page to set and retrieve the profile properties. To do so, you create an event handler for the click event of the Submit button in the .vb file.

Code
Partial Class Profiles Inherits System.Web.UI.Page Sub Submit_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Submit.Click

End Class

Then you use the Profile method to specify the profile property names defined in the web.config file. In this example, you use Profile.Birthday and Profile.Age.

Graphic
You add this code using the Profile method: Profile.Birthday = Server.HtmlEncode(textBirthday.Text) labelBirthday.Text = Profile.Birthday Profile.Age = Server.HtmlEncode(textAge.Text) labelAge.Text = Profile.Age End Sub

Code
Partial Class Profiles Inherits System.Web.UI.Page Sub Submit_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Submit.Click Profile.Birthday = Server.HtmlEncode(textBirthday.Text) labelBirthday.Text = Profile.Birthday Profile.Age = Server.HtmlEncode(textAge.Text)

labelAge.Text = Profile.Age End Sub

End Class

You then create a Page_Load handler to display user values every time a user requests the page. This code will display the Profile.Birthday and Profile.Age values every time the page is accessed.

Graphic
You add this code with the Page_Load handler: Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load labelBirthday.Text = Profile.Birthday labelAge.Text = Profile.Age End Sub

Code
Partial Class Profiles Inherits System.Web.UI.Page Sub Submit_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Submit.Click Profile.Birthday = Server.HtmlEncode(textBirthday.Text) labelBirthday.Text = Profile.Birthday Profile.Age = Server.HtmlEncode(textAge.Text) labelAge.Text = Profile.Age End Sub Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load labelBirthday.Text = Profile.Birthday labelAge.Text = Profile.Age End Sub End Class

Finally, you open the .aspx page code to ensure the Submit button has the click event associated with the event handler created in the .vb page. In this example, the code is OnClick="Submit_Click".

Code

<p> <asp:Label ID="Label1" runat="server" style="font-weight: 700" Text="Birthday: "></asp:Label> </p> <p> <asp:TextBox ID="textBirthday" runat="server"></asp:TextBox> </p> <p> <asp:Label ID="Label2" runat="server" style="font-weight: 700" Text=" Age: "></asp:Label> </p> <p> <asp:TextBox ID="textAge" runat="server"></asp:TextBox> </p> <p> <asp:Button ID="Submit" runat="server" Text="Submit" OnClick="Submit_Click"/> </p> <p> <asp:Label ID="labelAge" runat="server"></asp:Label> </p> <p> <asp:Label ID="labelBirthday" runat="server"></asp:Label> </p> </form> </body> </html>

Question
You are enabling profile properties for a web form, and you want to ensure that profile properties are enabled for only authenticated users. Complete the code in the web.config file to do this. Code
<system.web> <profile> <properties> <add name="Birthday" type="System.String" /> <add name="Age" type="System.String" /> </properties> </profile> <INSERT THE MISSING CODE /> </system.web>

Answer
You type anonymousIdentification enabled="false" to enable profile properties for only authenticated users.

Correct answer(s): 1. anonymousIdentification enabled="false"

Question
Michelle wants to enable profile properties for a web form so that user values are stored when the Enter button is clicked. She has already edited the web.config file. What steps should she perform next? Options: 1. 2. 3. 4. Define all profile properties Create an event handler for the Enter button's click event Check the web form's page code Specify whether profile properties are enabled for anonymous users

Answer
Option 1: Incorrect. You define profile properties in the web.config file. Michelle has already edited this file. Option 2: Correct. Michelle should create an event handler for the Enter button's click event in the .vb file. Option 3: Correct. Michelle should check whether the Enter button has the click event associated with the event handler created in the .vb page. Option 4: Incorrect. You specify whether profile properties are enabled for anonymous users in the web.config file. Michelle has already edited this file. Correct answer(s): 2. Create an event handler for the Enter button's click event 3. Check the web form's page code

Summary
ASP.NET offers client-side and server-side state management options for storing and managing state information. On the client-side, you can use five options to manage state data ViewState, ControlState, hidden fields, cookies, and query strings. On the server-side you can use three options to manage state data application state, session state, and profile properties.

To use profile properties for managing state data, you need to configure the web.config file, the aspx page, and the .aspx page's .vb file.

Event Handling in ASP.NET 4.0


Learning Objectives
After completing this topic, you should be able to

identify the steps for handling events recognize the steps for using generic handlers in ASP.NET

1. Handling events in ASP.NET 4.0


In programming models, events are user actions, such as a mouse click, or system and program actions, such as hardware failure. When an event occurs, it is sent as a message to an event handler. The event handler analyzes the message and responds to the event using predefined code. ASP.NET enables you to create event-based web pages. For example, you can add a button on a web page and create an event handler in code to indicate what happens when the button is clicked. However, events in ASP.NET function differently than events in HTML and client-based applications. In client-based applications, events are raised and handled within the client. In ASP.NET, events raised in the client are sent to the web server through HTTP. The web server invokes the event handler associated with the event, which then uses an appropriate method in the code to send a response. As an ASP.NET developer, you will often work with four common types of events: page events Page events are raised at the page level. For example, when a user requests a page, the Load event is raised and sent to the web server. This event is then handled by the event handler created for the requested page. Other examples of page events include requests for initializing a page and events to notify that a page has completed loading. control events Control events are raised when a user interacts with a control. For example, when a user clicks a button, an event is raised and sent to the web server. Such an event is then handled by the event handler created for that control in the code of the page. application events, and Application events affect an entire application. For example, when a client first requests a resource, such as a web page, in an application, the Application_Start event is raised. If an error occurs while starting the application, the Application_Error event is raised.

session events Session events signal the start or the end of a new user session. For example, the Session_OnStart event is raised when a new session starts, and the Session_OnEnd event is raised when a session expires. Say you have created a page that enables users to subscribe to your e-mail service using a field and a Submit button. You want to add an event handler that manages the page's Load event. To do so, you use the Page class, which provides a default method to handle page events. To create an event handler for a page, you create a method named Page_<event>. For example, you create the Page_Init method to create an event handler for the Initialize event.

Try It
In this example, you want to create an event handler for the Load event. To complete the task 1. Type Page_Load and click the Submit button The Courseware Player cannot recognize input from your keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key. Code:
Partial Class _Default Inherits System.Web.UI.Page Sub INSERT THE MISSING CODE(ByVal sender as Object, ByVal e As EventArgs)

An event handler for the Load event is created.

Outcome
The completed code is: Code:
Partial Class _Default Inherits System.Web.UI.Page Sub Page_Load(ByVal sender as Object, ByVal e As EventArgs)

In ASP.NET, pages post back to themselves and reload controls in their default state every time they are requested. However, in a web form, you would not want this to happen when a user clicks a control. For example, when a user clicks the Submit button to post the page back to the server, you would want the page to display a result message instead of reloading in its original state. To ensure that this happens, you enable the IsPostBack property, which informs the server whether the page is being loaded for the first time or is a post back.

You enable this property using an If statement with the Not Page.IsPostBack keyword. This qualifies the property in the statement condition.

Code
Partial Class _Default Inherits System.Web.UI.Page Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 'If 1st request, Page.IsPostBack is false If Not Page.IsPostBack Then Response.Write("1st Request") 'If not 1st request, Page.IsPostBack is true Else Response.Write("The page has been posted back.") End If End Sub End Class

ASP.NET also automatically binds all page events to their corresponding Page_<event> methods. This happens because the AutoEventWireup attribute is set to true by default in the @ Page directive in the page code. You can prevent ASP.NET pages from automatically searching for methods that use the Page_<event> name by setting the AutoEventWireup attribute to false.

Code
<%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Email Subscription</title> </head> <body> <form id="form1" runat="server"> <div> Please enter your email address in the text box to subscribe to the email service:<br /> <br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" Text="Submit" /> </div> </form>

</body> </html>

Supplement
Selecting the link title opens the resource in a new browser window. Launch window View all the stages and events involved in the lifecycle of an ASP.NET page. Launch window In addition to the Load event, you also want to create an event handler that manages the Submit button's click event. In Visual Basic, you can do this by creating an event handler with a custom name. You use the name SubmitClicked in this example.

Code
Partial Class _Default Inherits System.Web.UI.Page Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 'If 1st request, Page.IsPostBack is false If Not Page.IsPostBack Then Response.Write("1st Request") 'If not 1st request, Page.IsPostBack is true Else Response.Write("The page has been posted back.") End If End Sub Protected Sub SubmitClicked(ByVal sender As Object, ByVal e As System.EventArgs) _

You then specify the method declaration that the event handler will handle. To do so, you use the Handles keyword with the method declaration. In this example, you want the event handler to handle the click event of the Submit button, whose control ID is Button1. So you enter Handles Button1.Click in the code.

Code
Handles Button1.Click

You then complete the code for the event handler.

Code

Dim b As Button = CType(sender, Button) Response.Write("You have successfully subscribed to the e-mail service.") 'Enter code below End Sub End Class

Note
You can also use the same event handler to handle events of multiple controls. As an alternative to using code, you can also create an event handler for a control using the design view in Visual Studio. To do so, you begin by selecting the control the Submit button in this example.

Note
Because you cannot select a page, you cannot use the design view to create an event handler for a page event. You then click the Events button in the Properties pane. The Properties pane shows a list of events for which you can create an event handler.

Try It
You want to create an event handler named SubmitClicked for the Submit button's click event. To complete the task 1. Type SubmitClicked in the Click field and click the Enter key provided The Courseware Player cannot recognize input from you keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key. Visual Studio automatically takes you to the code view. The event handler, the Handles keyword, and method declaration are automatically added to the code. Also, the cursor is automatically placed in the position where you type the event handler code.

Note
You can also create an event handler in the Code view by selecting the required control and event in the drop down boxes at the top of the view. Users typically submit an ASP.NET web form using a button. Therefore, ASP.NET enables you to set the event handler that should be executed when a button is clicked from within the control

itself using the OnClick property. Other controls have similar properties that enable event handlers to be associated with their events, for example the OnTextChanged property of the TextBox control.

Try It
Suppose that when a button is clicked, you want it to trigger an event that changes the text on the button to "Thank you". To do this, you need to configure the OnClick property so that the Submit event handler is triggered when the button is clicked. To complete the task 1. Type OnClick="Submit" and click the Submit button provided The Courseware Player cannot recognize input from your keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key. Code:
<script runat="server"> Sub Submit(o As Object, e As EventArgs) button1.Text="Thank you" End Sub </script> <html> <body> <form id ="Form2" runat="server"> <asp:Button id="button1" Text="Click to accept" _runat="server" INSERT THE MISSING CODE/> </form> </body> </html>

When the button is clicked, the Submit procedure will be invoked.

Outcome
The completed code is: Code:
<script runat="server"> Sub Submit(o As Object, e As EventArgs) button1.Text="Thank you" End Sub </script> <html> <body>

<form id ="Form2" runat="server"> <asp:Button id="button1" Text="Click to accept" _runat="server" OnClick="Submit"/> </form> </body> </html>

As explained earlier, ASP.NET pages post back to themselves. However, you may sometimes want a page to post back to another page instead of itself. For example, if you have a web form spread across several pages, you would want the controls on the first page to post the information selected by the user to the second page. Previously, developers used two methods to post back a page to another page:
Response.Redirect,

or You can use the Response.Redirect method for a control to redirect users either to a page on the same server or to a page on an external server. For example, you use Response.Redirect("Form2.aspx") if the page Form2.aspx is on the same server, and use Response.Redirect("http://www.website. com/Form2.aspx") if the page is located on an external server. method is faster than the Response.Redirect method, but you can only use it to transfer users to a page located on the same server. For example, you enter Server.Transfer("Form2.aspx") to transfer users to the page Form2.aspx on the same server.

Server.Transfer The Server.Transfer

To enable you to post back a page to another page, ASP.NET 4.0 provides an additional method called cross-page posting. Say you created a web page that your employees can use to find information about other employees by specifying a name, position, and region. The form includes two buttons Submit and Provide More Information. When a user clicks the Provide More Information button, you want to direct them to another page named MoreInfo.aspx.

Try It
To do this, you open the code of the aspx page and use the PostBackUrl property for the button. To complete the task 1. Type PostBackUrl="~/MoreInfo.aspx" and click the Submit button provided The Courseware Player cannot recognize input from your keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key.

Code:
</p> <br /> <asp:Button ID="Button1" Runat="server" Text="Submit page to itself" OnClick="Button1_Click" /> <asp:Button ID="Button2" Runat="server" Text="Submit page to Page2.aspx" INSERT THE MISSING CODE /> <p> <asp:Label ID="Labell" Runat="server"></asp:Label></p> </form> </body> </html>

Users will be directed to the page MoreInfo.aspx when they click the Provide More Information button.

Outcome
The completed code is: Code:
</p> <br /> <asp:Button ID="Button1" Runat="server" Text="Submit page to itself" OnClick="Button1_Click" /> <asp:Button ID="Button2" Runat="server" Text="Submit page to Page2.aspx" PostBackUrl="~/MoreInfo.aspx" /> <p> <asp:Label ID="Labell" Runat="server"></asp:Label></p> </form> </body> </html>

Question
In a web form, you have a checkbox with the control ID C2. You have created an event handler named CBChecked that handles the CheckChanged event of this checkbox. Now complete the code to enable the event handler to handle this event. Code
Protected Sub CBChecked(ByVal sender As Object, ByVal e As System.EventArgs) _ INSERT THE MISSING CODE 'Enter code below End Sub End Class

Answer

You enter Handles C2.CheckChanged to enable the CBChecked event handler to handle the CheckChanged event raised by your checkbox. Correct answer(s): 1. Handles C2.CheckChanged

Question
You have created a Page_Load event handler for the Load event of an ASP.NET web page. Now you want to ensure that the web server can recognize whether a page is loading for the first time or is a post back from the client. Complete the code to do this. Code
Partial Class _Default Inherits System.Web.UI.Page Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 'If 1st request, Page.IsPostBack is false INSERT THE MISSING CODE Then Response.Write("1st Request") 'If not 1st request, Page.IsPostBack is true Else Response.Write("The page has been posted back.") End If End Sub End Class

Answer
You enter If Not Page.IsPostBack to enable the web server to recognize whether a page is loading for the first time or is a post back. Correct answer(s): 1. If Not Page.IsPostBack

2. Handling events using alternate methods


In addition to the methods described earlier, you can also handle page events by

overriding the event-raising method, or adding delegates

You can create your own method to handle events by overriding the default method. To do this, your code must inherit from the base class that publishes the event.

Code
Protected Overrides Sub OnInit(e as EventArgs) Response.Write("It works.") MyBase.OnInit(e) End Sub

To define an event-handling method, you use the Overrides keyword on your own method to override the default event-raising method of the base class. You may want to preserve the functionality of the base class method. You do this by invoking the original method using the MyBase keyword. This keyword points back to the original method of the inherited class.

Code
Protected Overrides Sub OnInit(e as EventArgs) Response.Write("It works.") MyBase.OnInit(e) End Sub

Suppose you want to add your own event handler for the Init event to display the message "It works." when the page initializes. To do this, you use the Overrides keyword on your own OnInit method. You then invoke the OnInit method of the base class, using the MyBase keyword to identify it, and pass it the appropriate arguments.

Code
Protected Overrides Sub OnInit(e as EventArgs) Response.Write("It works.") MyBase.OnInit(e) End Sub

When you override an event-raising method to create a handler, ASP.NET requires that the class of the event raiser and the event handler be the same. Alternatively, to achieve more flexibility, you can use delegates to specify an event handler. A delegate points to an event handler in a class that does not derive from the class that publishes the event. Delegates also provide other advantages. They enable you to attach a single event handler to multiple events, attach multiple event handlers to a single event, and dynamically add and remove event handlers.

Graphic

The syntax displayed in the graphic is: Public Delegate Sub EventHandler(sender as object, e as EventArgs) The publisher maintains a list of delegates for each event. These delegates are invoked by the same method that raises the event. The signature of the event handler method must match the event handler delegate defined by the publisher.

Graphic
The syntax displayed in the graphic is: Public Delegate Sub EventHandler(sender as object, e as EventArgs) To add a delegate to an event, you can use the AddHandler keyword. This keyword takes two arguments the event and the event handler to which the delegate points. You precede the name of the event handler using the keyword AddressOf.

Graphic
The syntax displayed in the graphic is: AddHandler Obj.Event, AddressOf Me.EventHandler

Note
The AddressOf keyword indicates a location point in memory. In this case, the location of the subroutine used as your event handler. Suppose you've created an event handler for the Load event of a web page.

Code
Protected Sub NewLoadEvent(sender as Object, e as EventArgs) Response.Write("The page has loaded.") End Sub

Try It
To ensure that the NewLoadEvent event handler is executed when the Load event occurs, you subscribe a delegate to the event. The delegate points to the event handler. To complete the task 1. Type AddHandler and click the Submit button provided The Courseware Player cannot recognize input from your keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key.

Code:
Protected Sub NewLoadEvent(sender as Object, e as EventArgs) Response.Write("The page has loaded.") End Sub INSERT THE MISSING CODE Me.Load, AddressOf Me.NewLoadEvent

The code automatically creates the delegate that points to the NewLoadEvent procedure and links it to the Load event.

Outcome
The completed code is: Code:
Protected Sub NewLoadEvent(sender as Object, e as EventArgs) Response.Write("The page has loaded.") End Sub AddHandler Me.Load, AddressOf Me.NewLoadEvent

Question
You've created an event handler, UpdateGraph, for the CalculatePay event. You now want to subscribe a delegate to the event, to ensure that the handler is invoked every time the event is raised. Complete the code to add the delegate. Code
INSERT THE MISSING CODE Me.CalculatePay, AddressOf Me.UpdateGraph

Answer
You type AddHandler to complete the code that adds the delegate. Correct answer(s): 1. AddHandler

3. Creating generic handlers


Generic event handlers are custom HTTP handlers that are implemented using the IHttpHandler interface in ASP.NET. They are created in web pages that have an .ashx extension.

You use a generic handler when you need to create a simple custom handler without creating a new assembly. Additionally, generic handlers involve less overhead than traditional handlers, require no special configuration with the web application, and can be easily reused by copying and pasting the .ashx file. Say a page in your ASP.NET web application includes a form that allows a user to choose a color and a continent. To reuse this form in your application, you want to create a generic handler that is invoked when the form loads. To create a generic event handler using Visual Studio 2010, you first right-click the root of your web site and select Add New Item.

Try It
You then create a new generic handler using the Add New Item dialog box that opens. In this example, you want to create a generic event handler named CustomHandler.ashx. To complete the task 1. Select Generic Handler 2. Type CustomHandler.ashx in the Name field and click Add A generic handler named CustomHandler.ashx is created in your web site root folder. When you create a generic handler using Visual Studio 2010, it automatically uses the filename to create a class - CustomHandler in this example. This class implements the IHttpHandler interface and adds the IsReusable property to allow the handler to be reused. The generic handler also provides sample "Hello World" content.

Graphic
The code that automatically includes the class CustomHandler is: Public Class CustomHandler : Implements IHttpHandler The code that implements the IHttpHandler interface and adds the IsReusable property is: IHttpHandler.IsReusable

Code
Imports System Imports System.Web Public Class CustomHandler : Implements IHttpHandler Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest context.Response.ContentType = "text/plain" context.Response.Write("Hello World") End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable Get Return False End Get End Property End Class

In the code, you then remove the sample content and enter the content you require. In this example, you create a form that shows colors as radio buttons, continents in a drop-down list, and a button named Select.

Graphic
In this example, you add this code to replace the sample content: Public Sub ManageForm(ByVal context As HttpContext) context.Response.Write("<html><body><form>") context.Response.Write("<b>What is your favorite color?</b></br>") context.Response.Write("<input type='radio' name='color' value='red'>Red</input></br>") context.Response.Write("<input type='radio' name='color' value='blue'>Blue</input></br>") context.Response.Write("<input type='radio' name='color' value='green'>Green</input></br>") context.Response.Write("<input type='radio' name='color' value='yellow'>Yellow</input></br>") context.Response.Write("<input type='radio' name='color' value='orange'>Orange</input></br>") context.Response.Write("</br><b>Where are you from?</b></br>") context.Response.Write("<select name='continent'>") context.Response.Write("<option> Africa</option>") context.Response.Write("<option> Asia</option>") context.Response.Write("<option> Australia</option>") context.Response.Write("<option> Europe</option>") context.Response.Write("<option> America</option>") context.Response.Write("</select>") context.Response.Write("</br></br>") context.Response.Write("<input type=submit name='Lookup' value='Select'></input>") context.Response.Write("</br>")

Code
<%@ WebHandler Language="VB" Class="CustomFormHandler"%> Imports System.Web Public Class CustomFormHandler

Implements IHttpHandler Public Sub ProcessRequest(ByVal context As HttpContext) Implements System.Web.IHttpHandler.ProcessRequest ManageForm(context) End Sub Public Sub ManageForm(ByVal context As HttpContext) context.Response.Write("<html><body><form>") context.Response.Write("<b>What is your favorite color?</b></br>") context.Response.Write("<input type='radio' name='color' value='red'>Red</input></br>") context.Response.Write("<input type='radio' name='color' value='blue'>Blue</input></br>") context.Response.Write("<input type='radio' name='color' value='green'>Green</input></br>") context.Response.Write("<input type='radio' name='color' value='yellow'>Yellow</input></br>") context.Response.Write("<input type='radio' name='color' value='orange'>Orange</input></br>") context.Response.Write("</br><b>Where are you from?</b></br>") context.Response.Write("<select name='continent'>") context.Response.Write("<option> Africa</option>") context.Response.Write("<option> Asia</option>") context.Response.Write("<option> Australia</option>") context.Response.Write("<option> Europe</option>") context.Response.Write("<option> America</option>") context.Response.Write("</select>") context.Response.Write("</br></br>") context.Response.Write("<input type=submit name='Lookup' value='Select'></input>") context.Response.Write("</br>")

To complete the generic handler, you then add the code to show the result when a user chooses a color and continent and clicks the Select button.

Graphic
In this example, you add this code to show the result: If context.Request.Params("continent") IsNot Nothing Then context.Response.Write("</br>Your are from: ") context.Response.Write(context.Request.Params("continent")) context.Response.Write("</br>Your favorite color is: ") context.Response.Write(context.Request.Params("color")) End If

Code
context.Response.Write("</br><b>Where are you from?</b></br>") context.Response.Write("<select name='continent'>") context.Response.Write("<option> Africa</option>") context.Response.Write("<option> Asia</option>") context.Response.Write("<option> Australia</option>") context.Response.Write("<option> Europe</option>") context.Response.Write("<option> America</option>")

context.Response.Write("</select>") context.Response.Write("</br></br>") context.Response.Write("<input type=submit name='Lookup' value='Select'></input>") context.Response.Write("</br>") If context.Request.Params("continent") IsNot Nothing Then context.Response.Write("</br>Your are from: ") context.Response.Write(context.Request.Params("continent")) context.Response.Write("</br>Your favorite color is: ") context.Response.Write(context.Request.Params("color")) End If context.Response.Write("</form></body></html>") End Sub Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable Get Return False End Get End Property End Class

Question
To avoid creating a new assembly and reuse a handler, Larry wants to create a generic handler in his web application. He has already added a new generic handler using Visual Studio 2010. What should he do next? Options: 1. 2. 3. 4. Create a class that implements the IHttpHandler interface Replace the sample content code with the required code Add the IsReusable property in the code of the generic handler Add the .ashx extension to the generic handler file

Answer
Option 1: Incorrect. Visual Studio 2010 automatically uses the generic handler's filename to create a class that implements the IHttpHandler interface. Option 2: Correct. Larry should replace the sample content with the required content in the generic handler file. Option 3: Incorrect. Visual Studio 2010 automatically adds the IsResuable property in the code of the generic handler's .ashx file. Option 4: Incorrect. Visual Studio 2010 automatically adds the .ashx extension when you create a new generic handler item. Correct answer(s):

2. Replace the sample content code with the required code

Summary
When using ASP.NET, you will work with many events, such as page, control, application, and session events. You can handle page events by either using the default class method, overriding the event-raising method, or adding delegates. You can handle control events using the Handles keyword in code or by using the Properties pane in Visual Studio 2010. ASP.NET also enables you to create generic events. You can create a generic event in Visual Studio 2010 by adding a new generic handler file that has an .ashx extension.

Table of Contents
| Print | Contents | Close |

Globalization and Accessibility with ASP.NET 4.0


Learning Objectives
After completing this topic, you should be able to

recognize the steps for localizing and globalizing ASP.NET web pages recognize the accessibility options in ASP.NET and identify the steps for creating an accessible web site

1. Enabling Globalization using ASP.NET


If your web application has a global audience, you may want to personalize your users' experience by enabling them to view web pages in their native languages. Although you can enable additional languages by re-creating each page, this is a time-consuming method. ASP.NET provides an easier way to do this by using resource files. A resource file is an XML file that allows you to store the text you want to translate in a particular language. For example, if a page contains the text Hello World with several images, you can configure a resource file to translate the text to Buenos das for Spanish speakers and another resource file to translate the text to Bonjour monde for French speakers instead of re-creating the entire page. You can also use resource files to show different calendar and daylight savings times and different formatting patterns for dates, currency, and numbers. You can, for example, enable German users to view the number 10.50 as 10,50.

Based on the language set in a user's browser, ASP.NET translates text snippets at runtime by accessing the appropriate resource file. You can use resource files in two ways: globally, or You can use a resource file globally for all pages in your web application by storing it in the App_GlobalResources folder at the root of the application. A global resource file is useful when you want to translate common text that occurs on many pages in your application. You need to maintain only one global resource file for every language your application supports. locally You can use a resource file locally for a particular page in your web application by storing it in the App_LocalResources folder at the root of the application. A local resource file is useful when you want to translate text for each control, such as buttons and labels, on a particular page. You need to maintain a separate local resource file for every page you want to translate. Say you have a web site for English speakers in the USA. However, you now also have customers based in Canada and Mexico. You want to ensure that French speakers in Canada and Spanish speakers in Mexico are able to view your home page Welcome.aspx in their respective languages.

Try It
To globalize a particular page, you first create a base local resource file for that page Welcome.aspx in this example. To complete the task 1. Select Tools - Generate Local Resource Visual Studio creates the App_LocalResources folder with a file named Welcome.aspx.resx in it. After creating the resource file, you edit it to enter the translated text. So you open the file Welcome.aspx.resx in Visual Studio. This file shows the names of all the controls you have added on the page with their English text. In this example, the resource file shows one button, one hyperlink, one image, two labels, one title, and two fields.

Graphic
The file is displayed in a table format. The names of the controls are displayed vertically under the Name column and their English text is displayed under the Value column.

You want to first create a resource file for Spanish, so you remove the English text from the Values column and replace it with the Spanish text to display for each control. You then save the Welcome.aspx.resx file as a different file in the App_LocalResources folder. A resource file can only be accessed by a browser if it has the appropriate culture code in its filename. For example, you use en-US for English in the United States and af-ZA for Afrikaans in South Africa. In this example, the resource file will be accessed by Spanish speakers in Mexico, so you save the file as Welcome.aspx.es-mx.resx. However, specifying the region is optional. So if you want to make the resource file available to all Spanish speakers regardless of their region, you name the file as Welcome.aspx.es.resx.

Note
Specifying the region is useful when the same language is used differently in different regions. For example, English used in the United States is marginally different from the English used in Great Britain. Using the same procedure, you also create a local resource file named Welcome.aspx.fr-ca.resx for French speakers in Canada. In the previous demonstration, the resource files were created for a particular page, and the translations provided in it cannot be used for other pages. However, if you have text that is repeated on several pages, you can create a global resource file for each language so that all pages can access them. Say the title "Welcome to Blastera" is visible on all pages in your web application. You want to create global resource files for Spanish and French speakers to translate this title on all pages. You begin by adding the App_GlobalResources folder at the root of your application. To do so, you right-click your web site root and select Add ASP.NET Folder - App_GlobalResources. You then need to create a base global resource file named LocalizedText.resx that contains the English text to be translated. To do so, you right-click the App_GlobalResources folder and select Add New Item.

Try It
You then use the Add New Item dialog box. To complete the task 1. Select Resource File 2. Type LocalizedText.resx in the Name text box and click Add

A resource file named LocalizedText.resx is created in the App_GlobalResources folder and opened automatically. You then name the text string as Text01 in the Name column, type Welcome to Blastera in the Value column, and click the save button to save the file. Using the same procedure, you then create a resource file named LocalizedText.es-mx.resx, type the string Text01 in the Name column, type Bienvenido a Blastera in the Value column, and save the file. Finally, you create a file named LocalizedText.fr-ca.resx file, type the string Text01 in the Name column, type Bienvenue Blastera in the Value column, and save it. Depending on a user's default browser language and region, the title on all pages will now be visible in either English, Spanish, or French. In most cases, letting a user view a page in a language based on the browser settings is helpful. In some cases, however, you may want to explicitly specify the language or number format that the web application or a web page uses. For example, for a page where you are selling a product, you may want the user's browser to choose the language but ensure that the currency is displayed in a particular format. In such cases, you can set two culture settings:
CurrentCulture, and The CurrentCulture

property determines and automatically displays the results of culture-dependent functions, such as date, number, or currency format. property determines which resource file must be used for a page.

CurrentUICulture The CurrentUICulture

You can set the CurrentCulture and CurrentUICulture properties either declaratively or programmatically. To set them declaratively for all pages, you use the <globalization> tag in the web.config file and set properties for uiculture and culture using culture codes. You need to specify both a language and a region for the CurrentCulture property for example, en-AU for English in Australia. Specifying the region is optional for the CurrentUICulture property. So to make your web application or a page available to all French speakers regardless of their region, you use only the code fr. In this example, the culture is set as de-De for German speakers in Germany and uiCulture is set as de for all German speakers.

Graphic

The code displayed in the example is <globalization culture="de-DE" uiCulture="de"/>

Code
<configuration> <system.web> <globalization culture="de-DE" uiCulture="de"/> </system.web> </configuration>

To set these two properties declaratively for a particular page, you use the <% @Page %> directive.

Graphic
The code displayed in the example is: <%@ Page culture="de-DE" uiculture="de" %>

Code
<%@ Page culture="de-DE" uiculture="de" %> <script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = "Hello World!" End Sub </script> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Hello World Page</title> <style type="text/css"> #form1 ....

Note
If you set the Culture and UICulture properties to auto, the browser automatically loads the first language specified in the settings.

To set the CurrentCulture and CurrentUICulture properties programmatically, you first import the System.Threading and System.Globalization namespaces. You then override the InitializeCulture method and use the CultureInfo class to specify the CurrentUICulture and CurrentCulture properties of a page or a thread.

Code
<%@ Import Namespace="System.Threading" %> <%@ Import Namespace="System.Globalization" %> <script runat="server"> Protected Overrides Sub InitializeCulture() Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim strLanguage As String = Request.UserLanguages(0) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR") Thread.CurrentThread.CurrentUICulture = New CultureInfo("fr-FR") End If MyBase.InitializeCulture() End Sub

When using ASP.NET, you can also select an encoding for aspx pages to let ASP.NET interpret the content of the page. ASP.NET can interpret three types of encodings ANSI codepage, UTF8, and UTF-16 (Unicode). You should ensure that the encoding of the ASP.NET file matches the encoding specified in the file under the @ Page encoding attributes. To set encoding, you set the properties of the fileEncoding, requestEncoding, and responseEncoding options in the <globalization> tag. This example shows the UTF-16 encoding being used.

Code
<configuration> <system.web> <globalization fileEncoding="utf-16" requestEncoding="utf-16" responseEncoding="utf-16" culture="en-US" uiCulture="en" /> </system.web> </configuration>

Question
Say you want to declaratively ensure that a web page loads the number formats used by English speakers in the USA. Which code snippet would you use to do this?

Options: 1. 2. 3. 4.
<%@ Page culture="en-US" %> <%@ Page uiculture="en-US" %> <%@ Page culture="en" %> <globalization culture="en-US"/>

Answer
Option 1: Correct. For a web page, you use the code <%@ Page culture="en-US" %> to load number formats used by English speakers in the USA. Option 2: Incorrect. For a web page, you use the code <%@ Page uiculture="en-US" %> to load the resource file that displays the web page language in English for people in the USA. Option 3: Incorrect. For a web page, you use the code <%@ Page culture="en" %> to load number formats used by English speakers regardless of their region. Option 4: Incorrect. You use the code <globalization culture="en-US"/> to load number formats used by English speakers in the USA for all pages in your web application. Correct answer(s): 1. <%@ Page culture="en-US" %>

SkillCheck
In your web application, the link Learn More is present on all pages. Using the text string name T1, ensure that it is translated to all pages as Fale conosco for Portuguese speakers in Brazil. Use the culture code pt-BR to do this. The App_GlobalResources folder is right-clicked for you. Task: 1. 2. 3. 4. Add a new item. Select the option that creates a resource file. Type an appropriate name for the resource file and create it. Specify a name for the text string, type the translated text, and save the file.

Answer
To complete the task Step 1: Select Add New Item Step 2: Select Resource File

Step 3: Type LocalizedText.pt-BR.resx in the Name field and click Add Step 4: Type T1 under the Name column, type Fale conosco under the Value column, and click the Save button

2. Enabling Accessibility using ASP.NET


In addition to globalizing your web application, you might also want to make it accessible to people with disabilities such as vision, hearing, and motion impairments. For example, you can include support for screen readers and text-only browsers, choose appropriate font size and colors, and provide a description of images used in the application. By making your web application accessible to people with disabilities, you can increase the number of users for your application. ASP.NET provides several features to make your web application accessible. You can enable keyboard navigation You can enable users that cannot operate a mouse to navigate your web application using the Tab key. Using the TabIndex property, you can specify the order in which controls on a page are highlighted when the Tab key is pressed. Additionally, using the AccessKey property, you can allow users to jump to a control on the page by pressing the Alt key with a shortcut key associated with that control. provide alternate text Providing descriptive alternate text for an image enables visually challenged people or people who use a text-only browser to learn what the image depicts. You can add alternate text for an image by using the AlternateText property. For decorative images that do not provide information, you can set the GenerateEmptyAlternateText property to true to provide blank alternate text. let screenreaders skip repeated links You can help screenreaders skip links such as menu names that are repeated across pages. You can do so for the CreateUserWizard, Menu, SiteMapPath, TreeView, and Wizard controls by setting the SkipLinkText property to a string. add table captions and headers You can specify captions and headers for a table to enable people using screenreaders to understand the layout of the table. You can specify a table caption by using the Caption and CaptionAlign properties. You can specify table headers by using the TableSection property. You can also use the AssociatedHeaderCellID property to provide a cell identifier. provide accessible login controls, and By default, ASP.NET login controls include accessibility features, such as labels for text fields and tab index settings for Input controls. associate a label control with another control You can use the AssociatedControlID property to associate a Label control with another control on the page. When a user clicks such a label, the control that it is

associated with gets clicked. For example, if you have a checkbox on a page, you can configure the label next to it so that users can select the checkbox by clicking the label. To make your web pages accessible to everyone, you should

provide titles for objects provide alternate text for images specify captions and row and column headers for tables use heading tags to format the font set keyboard navigation in a logical order write appropriate link names attach files, if any, of a common format support formatting options for screenreaders

Say you want to make the home page of your web application, Welcome.aspx, accessible. You want to first add alternate text for the company logo, so you select the image. Then, in the Properties pane, you enter the value of the AlternateText property as Blastera Logo.

Note
To view the Properties pane, you select View - Properties Window. You now want to ensure that the User name field is the first control that is selected when the Tab key is pressed. So you select this field and set the value of the TabIndex property to 1. If you set the TabIndex property value of a control as blank or zero, the control is selected after controls that have a TabIndex property greater than zero. You can also exclude a control from the tabbing order by setting its TabIndex property value as 1.

Try It
You now want to enable users to press Alt+U to jump to the User name field. To complete the task 1. Type U as the value for the AccessKey property and click the Enter key provided The Courseware Player cannot recognize input from you keyboard Enter key. Therefore, please click the Enter button provided instead of pressing the Enter key.

The AccessKey property for the User name field is set as U. You now want to ensure that the User name field is selected when a user clicks the User name label. So you select the User name label and click the AssociatedControlID property dropdown list in the Properties pane. This drop-down list displays the IDs of all the controls on the page. In this example, you have set the ID of the User name field as TextBox1, so you select this option from the drop-down list to associate the User name label with the User name field. You then set the values of the TabIndex and AccessKey properties for the Password field as 2 and P respectively. You also associate the Password label with the Password field. You set the TabIndex and AccessKey properties for the Login button as 3 and L respectively. Finally, you set the TabIndex and AccessKey properties for the About Us link as 4 and A respectively and save the changes.

Question
Jim wants to ensure that a radio button on a web form is selected when a user clicks the label next to it. How can he ensure this in ASP.NET? Options: 1. 2. 3. 4. Set the TabIndex property value of the label as 1 Provide the radio button's name as the alternate text for the label Specify the AccessKey property value of the label as L Associate the label with the radio button

Answer
Option 1: Incorrect. Setting the TabIndex property value of a control as 1 ensures that it is selected when a user first presses the Tab key. Option 2: Incorrect. Alternate text is provided to make images accessible. It is not used for labels. Option 3: Incorrect. Specifying the AccessKey property value of a control as L would help a user select that control by pressing Alt+L. Option 4: Correct. Jim should associate the label with the radio button to allow users to select the radio button by clicking the label. Correct answer(s):

4. Associate the label with the radio button

SkillCheck
You are configuring your web site's home page to make it accessible. Ensure that the Welcome page is selected when the user presses the Tab key the second time. Task: 1. Select the control you want to configure. 2. Use the Properties pane to specify an appropriate value for the TabIndex property.

Answer
To complete the task Step 1: Select the Welcome link Step 2: Type 2 as the value of the TabIndex property in the Properties pane and click the Enter key provided

Summary
Using ASP.NET, you can globalize your web pages to ensure that people living in different regions can view your web pages in their native languages and number formats. You can either use a local resource file to translate text on a particular web page or you can use a global resource file to translate common text snippets on several pages in your web application. By setting CurrentCulture and CurrentUICulture properties, you can also determine the language and number format that your web application or web page should use regardless of a user's browser settings. You can make your web pages accessible to physically challenged users and users that don't use modern web browsers. You can do so by adding alternate text for images, enabling keyboard navigation, providing shortcut keys, and allowing selection of a control by clicking a label. | Print | Contents | Close |

Adding .NET Controls and Event Handling


Learning Objectives
After completing this topic, you should be able to

wire controls on a web page for event handling

perform basic event handling using a generic handler

Exercise overview
In this exercise, you're required to create an event and a generic handler for an ASP.NET web application. This involves the following tasks:

create an event handler for an ASP.NET control, and create a generic handler

Task 1: Creating an event handler


You are creating an ASP.NET web site that enables customers to book a room online. On the page Book.aspx, you have added three controls a calendar, a drop-down list, and a button. Customers will use them to choose a date, the number of people, and create the booking. You want to create an event handler for the drop-down list. Using Visual Studio 2010, create an event handler named NumberSelect for the TextChanged event of the Number of Guests drop-down list. The Properties tab is already open. Steps list Instructions 1. Select the Number of Guests drop-down list 2. Click the Events button in the Properties pane 3. Type NumberSelect in the TextChanged text box

Task 2: Creating a generic handler


You now want to include a web form that customers can use to provide feedback about their experience in the hotel. For this form, you want to create a simple generic handler so that you don't have to create a new assembly. Create a generic handler named MyHandler with an appropriate extension. You have already right-clicked the root of your web site. Steps list Instructions 1. Select Add New Item 2. Select Generic Handler 3. Type MyHandler.ashx in the Name text box and click Add

You then replace the sample data provided by Visual Studio 2010 with your own code. You successfully created an event handler for an ASP.NET control and a generic handler for an ASP.NET web site.

Table of Contents

S-ar putea să vă placă și