Module 2: Using Web Controls

34 373 0
Module 2: Using Web Controls

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Module 2: Using Web Controls Contents Overview What Are Web Controls? Using Intrinsic Controls Using Input Validation Controls 18 Selecting Controls for Applications 28 Lab 2: Creating a Form that Performs Validation 29 Review 30 Information in this document is subject to change without notice The names of companies, products, people, characters, and/or data mentioned herein are fictitious and are in no way intended to represent any real individual, company, product, or event, unless otherwise noted Complying with all applicable copyright laws is the responsibility of the user No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Microsoft Corporation If, however, your only means of access is electronic, permission to print one copy is hereby granted Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property  2000 Microsoft Corporation All rights reserved Microsoft, BackOffice, MS-DOS, Windows, Windows NT, are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A and/or other countries Other product and company names mentioned herein may be the trademarks of their respective owners BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls iii Instructor Notes Presentation: 120 Minutes Lab: 60 Minutes This module provides students with an overview of Web controls Students will learn how to use different types of Web controls in their applications In the lab, students will add intrinsic Web controls, validation controls, and the calendar control to a page They will also perform the steps to test whether a page is valid After completing this module, students will be able to: ! Add Web controls to an ASP.NET page ! Use properties, methods, and events of Web controls ! Validate user input on an ASP.NET page using input validation controls ! Bind two controls together Materials and Preparation This section provides the materials and preparation tasks that you need to teach this module Required Materials To teach this module, you need the following materials: ! Microsoft® PowerPoint® file 2063A_02.ppt ! Module 2, “ Using Web Controls” (2063A_02.doc) ! Lab, “Using Web Controls” (2063A_L02.doc) Preparation Tasks To prepare for this module, you should: ! Read all of the materials for this module ! Complete all the demonstrations ! Complete the lab BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY iv Module 2: Using Web Controls Module Strategy Use the following strategy to present this module: ! What Are Web Controls? Web controls are just a category of server controls Everything students learned in module about server controls applies to Web controls too This section provides students with an overview of Web controls When talking about the rich controls say something about the rich controls, because rich controls are not covered elsewhere in the course Point them to NET SDK for more information about these controls Students will be using the Calendar control in the lab, but you won't be covering it in the module The lab directions cover what attributes to set, and so on ! Using Intrinsic Controls In this section, students learn about intrinsic controls and how they are used When talking about intrinsic controls, talk about how they compare to HTML controls and the differences between using these controls and standard HTML controls The section also talks about handling events for these controls Handling events in ASP.NET is very different than handling events in ASP and you may have to spend more time on it All of the controls are not covered in this section Point students to the NET Framework SDK documentation for more information on the controls that aren't covered ! Using Input Validation Controls At the start of the section, bring out the need for using validation controls Remind students of how much code they had to write in order to validate user input When talking about the different input validation controls, tell them the function of each (given in the student notes) When teaching how to use the validation controls, you could start by showing them an example of code needed to validate the range of the given input by using ASP Then show them how they could easily it by using the RangeValidator control At the end of the section, ask students to summarize the advantages of using validation controls All of the controls are not covered in this section Point students to the NET Framework SDK documentation for more information on the controls that aren't covered Students will be using the RegularExpressionValidator control in the lab, but the directions explain how to set the attributes ! Selecting Controls for Applications Provide students with examples of when they would use a particular type of server control BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls Overview Topic Objective To provide an overview of the module topics and objectives ! ! Using Input Validation Controls ! In this module, you will learn how to use Web controls in your applications Using Intrinsic Controls ! Lead-in What Are Web Controls? Selecting Controls for Applications Web controls are designed to provide a simple way to add functionality, such as displaying data or selecting dates, to a Web page Web controls include traditional form controls such as buttons and text boxes as well as complex controls such as tables and calendar control After completing this module, you will be able to: ! Add Web controls to an ASP.NET page ! Use properties, methods, and events of Web controls ! Validate user input on an ASP.NET page using input validation controls ! Bind two controls together BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls What Are Web Controls? Topic Objective To remind students of the difference between Web controls and HTML controls and list the categories of Web controls available ! ! Lead-in HTML Controls Web Controls # Intrinsic controls # Input Validation controls # Rich controls # In the previous chapter, you worked with HTML controls Let’s now look at how to use Web controls List-bound controls ASP.NET uses server controls extensively to simplify the task of programming Web pages You can change many HTML elements into server controls by adding the runat=server attribute to the element tag However, ASP.NET includes new controls, called Web controls that have built-in functionality and are the preferred controls to use in an ASP.NET page Web controls include traditional form controls such as buttons and text boxes as well as complex controls such as tables They also include controls that provide commonly used form functionality such as displaying data in a grid, choosing dates, and so on There are four sets of Web controls: ! Intrinsic controls map to simple HTML elements ! Validation controls provide a variety of data validation ! Rich controls provide rich user interface and functionality Currently ASP.NET ships with two rich controls, the Calendar and the AdRotator controls ! List-bound controls provide data flow across a page The DataGrid, DataList, and Repeater controls constitute an interrelated set of Web controls These controls render HTML to display the contents of a list or data source to which they are bound Hence, they are collectively referred to as “list-bound controls.” Note You will learn how to display data from databases using list-bound controls in Module “Using ADO.NET to Access Data.” BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls Web controls exist within the System.Web.UI.WebControls namespace You create them using the asp: namespace You not have to import this namespace into your ASPX page in order to use these controls For example, the following sample code creates a button Web control: Note All controls must be well formed and must not overlap Unless otherwise noted, elements must be closed, either with an ending slash within the tag, or with a closing tag For example, or < asp:Button runat=server > For more information about the Web controls available with ASP.NET, go to the Web Controls section in the ASP.NET SDK documentation BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls $ Using Intrinsic Controls Topic Objective To introduce the topics included in this section Lead-in Web controls include intrinsic, validation, rich, and list-bound controls In this section, you will learn more about intrinsic controls ! What Are Intrinsic Controls? ! Using Intrinsic Controls on a Form ! List of Intrinsic Controls ! Demonstration: Adding Intrinsic Controls to a Page ! Handling Intrinsic Control Events ! Linking Two Controls Together ! Demonstration: Linking Two Controls Together Intrinsic controls are designed to be replacements for the standard set of HTML controls This section describes intrinsic controls and explains how to use them in an ASP.NET page BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls What Are Intrinsic Controls? Topic Objective To describe intrinsic controls ! Lead-in One of the biggest problems with using HTML controls has been the lack of a consistent naming convention Intrinsic controls are designed to replace HTML controls Provide standard naming convention, with standard properties for controls ! Include properties specific to the control ! Create browser-specific HTML Standard Standard Intrinsic controls are used as an alternative to HTML controls You use Web controls the same way you use HTML controls The most important difference is the prefix tag asp: that is added before every Web control For example, you can add a Label control to a form using the following line of code: Intrinsic Web controls provide the following benefits: ! Provide a standard naming convention for similar controls ! Provide common properties for all controls ! Include strongly typed properties specific to the control ! Create browser-specific HTML Standard Naming Convention One of the problems with HTML controls has been the lack of consistent naming convention for similar controls Intrinsic controls eliminate this problem, as shown in the following examples Example The following lines of code declare a radio button, a check box, and a button All of these controls are input controls; however, they all behave in a different manner BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls Intrinsic controls provide an alternative way of declaring different controls The following lines of code use intrinsic Web controls to declare a radio button, a check box, and a button: Include common properties for controls In ASP.NET, common properties for intrinsic controls have the same name For example, when you want to set the background color for a control you always use the same attribute irrespective of the control For example, all controls have a Text property that sets the text corresponding to the control Controls also have BackColor and ForeColor properties Setting the BackColor="red" property sets the background color to red for any control Control-Specific Properties Intrinsic Web controls also have a set of properties that relate specifically to the control Check Box For example, a check box has a Checked property that indicates whether the check box is checked or not The following sample code creates a check box labeled Standard that is initially checked List Box Some properties of Web controls are available only at run time For example, the list box and drop-down list boxes have the following properties that make it easy to read their selected value: ! SelectedItem is the value of the item selected in the list box ! SelectedItems is the collection of values of the items selected in a multiselection list box Create Browser-Specific HTML Although Web controls are easily added to a page, they are powerful controls When a page is rendered for a browser, the Web controls determine which browser is requesting the page and then deliver the appropriate HTML For example, if the requesting browser supports client-side scripting, such as Internet Explorer 4.0 or greater, then the controls create client-side script to implement their functionality But if the requesting browser does not support client-side script, then the controls would create server-side code and require more round trips to the server to obtain the same functionality BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 16 Module 2: Using Web Controls Linking Two Controls Together Topic Objective To explain how to bind one control to the contents of another control ! Binding one control to another is useful for taking values from list boxes or drop down lists Lead-in As mentioned in the previous topic, a data source for a control can be the contents of another control You selected: Text="" /> You can bind one control to the contents of another This is particularly useful for taking values from list boxes or drop-down lists Example The following example demonstrates how to bind a Label control to the contents of a drop-down list You set the Text attribute of the Label control to the Selected Item of the lstLocation list using the binding tags : Notice that the autoPostBack property of the drop-down list is set to True, which causes automatic post back whenever the value of the list box changes Sub Page_Load (Sender As Object, E As EventArgs) SelectedValue.DataBind End Sub Boston New York London Amsterdam

You selected:

BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 17 Demonstration: Linking Two Controls Together Topic Objective To introduce the demonstration Lead-in In this demonstration, you will see how to bind a Label control to a list box Delivery Tip In this demonstration, you will see how to bind a Label control to a list box Open the page you created in the last demo, intrinsic.aspx Add a label control to the page Bind the label control to the listbox by setting its Text attribute to: " " Create a Page_Load event and call Page.DataBind() Save and test The completed code for this demonstration is in the binding.aspx page BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 18 Module 2: Using Web Controls $ Using Input Validation Controls Topic Objective To introduce the topics in this section Lead-in Validating user input is a common scenario in a Webbased application For production applications, developers often end up spending a lot of time coding for validation tasks ! Input Validation Controls ! Adding Input Validation Controls to a Form ! Validating an Entire Page ! Demonstration: Adding Input Validation Controls ! Advantages of Using Input Validation Controls In HTML 3.2, validating data is a difficult process Validation code can be run either on the client or on the server, or both Each time you recieve a request, you not only need to write code that checks the input, you need to write error messages to help the user to correctly fill in the form This is a taxing process for end users, developers, and servers With the introduction of input validation controls in ASP.NET, the task of validating input is easier than it has been in the past In this section, you will learn about the advantages of using input validation controls You will also learn how to add these controls to an ASP.NET page BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 19 Input Validation Controls Topic Objective To list the input validation controls available in ASP.NET Lead-in There are five validation controls that ship with ASP.NET ! RequiredFieldValidator ! CompareValidator ! RangeValidator ! RegularExpressionValidator ! CustomValidator Validation controls are added to an ASP.NET page like other server controls There are controls for specific types of validation, such as range checking or pattern matching, plus a RequiredFieldValidator control that ensures a user does not skip an entry field The validation controls have both uplevel and downlevel client support Uplevel browsers perform validation on the client (using JavaScript and DHTML) Client-side validation enhances the validation scheme by checking user input as the user enters data This allows errors to be detected on the client before the form is submitted, preventing the round-trip necessary for server-side validation In uplevel checking, if there is an error in user input, a trip is not made to the server; instead the associated error messages are shown on the client Downlevel browsers perform validation on the server Both scenarios use the same programming model Note More than one input control can be associated with a web control For example, there can be a required and compare validator for the same text box web control Also, the validation controls also work with html web controls BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 20 Module 2: Using Web Controls The following table lists the validation controls included in the ASP.NET Framework Validation control Function RequiredFieldValidator Checks whether value has been entered into a control CompareValidator Compares an input control to a fixed value or another input control It can be used for password verification fields, for example It is also possible to typed date and number comparisons RangeValidator Much like CompareValidator, but can check that the input is between two values or the values of other input controls RegularExpressionValidator Checks that the entry matches a pattern defined by a regular expression This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on CustomValidator This allows you to write your own code to take part in the validation framework ValidationSummary Collects all validation errors and places them in a list within the page For more information about using the Input Validation controls, see the NET Framework SDK documentation BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 21 Adding Input Validation Controls to a Form Topic Objective To explain how to use input validation controls on an ASP.NET page Lead-in Let’s look at how these validation controls are added to a page ! Properties: # ControlToValidate # ErrorMessage # Display The standard code used to add input validation controls to a form is as follows: In the above code, controlToValidate is the id of the control whose input is being validated (a text box, in most cases) The errorMessage property is the error message that is displayed if the input is not valid, and the display property indicates how the validation control will be rendered in the page If you set the display property to static implies that each validation control takes up space even when no error message text is visible, allowing you to define a fixed layout for the page Validation controls cannot occupy the same space on the page, so you must give them each separate locations on the page Setting the display property to dynamic means that the layout of the page changes, sometimes causing controls to jump around In addition to the above-mentioned required properties, each validation control has more specific properties that define how the control should behave The following examples show how to add validation controls BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 22 Module 2: Using Web Controls RequiredFieldValidator control Use the RequiredFieldValidator control to require input in a field The following code shows how to use the RequiredFieldValidator control RangeValidator control To test whether an input value falls within a given range, use the RangeValidator control The RangeValidator control uses two additional properties to perform its validation–MinimumControl and MaximumControl These properties define the minimum and maximum values of the valid range Important In the beta version of Visual Studio.NET, the MinimumControl and MaximumControl properties will be replaced by MinimumValue and MaximumValue In the following example, the txtAge field must have a value between 18 and 50 If the value does not fall within the range, an error message is displayed and no trip to the server occurs CompareValidator control To use one control to test the validity of a second control, or to test input against a specific value, use the CompareValidator control The CompareValidator control uses the following additional properties to perform its validation: ! ValueToCompare or ControlToCompare Set ValueToCompare to compare to a constant value Set ControlToCompare to the ID of another control to compare against If you set both ValueToCompare and ControlToCompare, ControlToCompare takes precedence BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls ! 23 Type The data type of the two values to be compared ! Operator The comparison to use Operators are specified with the name of the comparison operators, such as Equal, NotEqual, GreaterThan, GreaterThanEqual, and so on The following shows an example in the aspx file of a Web Form Textbox control with required field validation A table is used to control layout In the following example, the txtAge field must have a value greater than or equal to zero BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 24 Module 2: Using Web Controls Validating an Entire Page Topic Objective To introduce the mechanisms available to determine if all controls on a page are valid Lead-in Sometimes you need to know if all the controls on a page are valid before performing some other action ! Page.IsValid property Sub Submit_click (s A Object, Sub Submit_click (s A Object, If Page.IsValid Then If Page.IsValid Then Message.Text = "Page is Message.Text = "Page is End If End If End Sub End Sub ! e As EventArgs) e As EventArgs) valid!" valid!" ValidationSummary control Sometimes you need to know if all the controls on a page are valid before performing some other action In fact, in client side validation, values are sent across to the server only when all controls are valid IsValid Property ASP.NET developers can check the Page.IsValid property at runtime to determine whether all validation server controls on a page are currently valid This provides a simple “one line” way to determine whether to proceed with business logic Sub Submit_click (s A Object, e As EventArgs) If Page.IsValid Then Message.Text = "Page is valid!" End If End Sub BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 25 Validation Summary Control If a validation control is in error, an error message may be displayed in the page by the validation control or in a ValidationSummary control elsewhere on the page The ValidationSummary control is displayed when the IsValid property of the page is false It “polls” each of the validation controls on the page and aggregates the text messages exposed by each ! The ValidationSummary updates itself without posting back if it detects errors ! The ValidationSummary can optionally display a message box to the user if there are errors BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 26 Module 2: Using Web Controls Demonstration: Adding Input Validation Controls Topic Objective To demonstrate using input validation controls on an ASP.NET page Lead-in In this demonstration, you will see how to add input validation controls to a form In this demonstration, you will see how to add input validation controls to text controls on a form Delivery Tip Open the page you created in the last demo intrinsic.aspx Add a RequiredField validator to the txtName text box See the file validation.aspx for an example Save and test the page Show the error message displayed when the Save button is clicked while the text box is blank View the source of the page to show that the control generated client-side code Open the page validate_all.aspx Show all the validation controls used Test the page Show how the Validation Summary control works and the Page.IsValid test in the click event procedure BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 27 Advantages of Using Input Validation Controls Topic Objective To describe the advantages of using the input validation controls in the ASP.NET framework ! ! Uses DHTML and JScript library to write client logic ! In HTML, validating data is a difficult process DTHML and scripting languages improve things somewhat However, coding for validating user input is still a time-consuming process for developers Create client-side and server-side validation ! Lead-in Provide immediate feedback to the user Allow enhancement of client-side validation and behavior Most Web sites perform their validation checks on the server However, most applications also need client-side validation checks The process of writing two versions of validation code can be extremely time consuming for developers Validation controls eliminate this problem because almost of the duplicated logic is encapsulated in the controls Validation controls check controls for a specific type of error condition and display a description of that problem In addition the controls create browser-specific code So if a client with Internet Explorer 4.0 or later uses the page, it can perform the same input validation that takes place on the server without client script Using validation controls has the following advantages: ! Provides immediate feedback to the user Immediate feedback is given to the user on whether the data entered is valid or not The error messages appear and disappear immediately after the bad input is entered/corrected ! Creates client-side and server-side validation If the browser supports client-side script, the controls error checking before posting the data to the server This saves the user time and reduces hits on the server ! Uses DHTML and JScript library to write client logicThe client logic is contained in a JScript library, so no ActiveX components or Java applets are used ! Allows enhancement of client-side validation and behavior An object model is exposed on the client to allow enhancement of clientside validation and behavior BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 28 Module 2: Using Web Controls Selecting Controls for Applications Topic Objective To describe appropriate situation for using different types of controls Use Web controls when: # Lead-in When creating Web Forms, you can use different classes of controls You prefer a Visual Basic-like programming model # You need specific functionality such as a calendar or ad rotator # You prefer an HTMLlike object model # You are working with existing HTML pages and want to quickly add Web Forms functionality You are writing a page that might be used by a variety of browsers # Use HTML controls when: # The control will interact with client and server script When creating ASP.NET pages, you can use different classes of controls You can mix control types on the same page For example, your ASP.NET page might include a form made up of Web controls plus an HTML control converted from an HTML element The following table summarizes some of the situations in which you would decide to use a particular control Type of control Use it when Web control You prefer a Visual Basic-like programming model You are writing a Web Forms page that might be viewed by a variety of browsers You need specific functionality such as a calendar or ad rotator that is available only as a Web Forms control You are creating applications with nested controls and want to be able to catch events at the container level HTML control You prefer an HTML-like object model You are working with existing HTML pages and want to quickly add Web Forms functionality Because HTML controls map exactly to HTML elements, any HTML design environment can support them The control will also interact with client and server script As a general rule, Web controls are more capable and have a richer object model than HTML controls If you are writing your ASP.NET page so that all processing occurs on the server, Web controls are a good choice BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls 29 Lab 2: Creating a Form that Performs Validation Topic Objective To introduce the lab Lead-in In this lab, you will create a form that uses validation controls to validate user input BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY 30 Module 2: Using Web Controls Review Topic Objective To reinforce module objectives by reviewing key points ! ! Validate user input on an ASP.NET page using input validation controls ! The review questions cover some of the key concepts taught in the module Use properties, methods, and events of Web controls ! Lead-in Add Web controls to an ASP.NET page Bind two controls together What is the prefix tag that you must use to create Web controls? asp: List the input validation controls included with ASP.NET RangeValidator, RequiredFieldValidator, CompareValidator, RegularExpressionValidator, CustomValidator How you create an event procedure for a button? Set up the event procedure in the button’s tag by setting the onclick property, then write the event procedure in a section BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY ... PURPOSES ONLY iv Module 2: Using Web Controls Module Strategy Use the following strategy to present this module: ! What Are Web Controls? Web controls are just a category of server controls Everything... PURPOSES ONLY Module 2: Using Web Controls What Are Web Controls? Topic Objective To remind students of the difference between Web controls and HTML controls and list the categories of Web controls. .. databases using list-bound controls in Module ? ?Using ADO.NET to Access Data.” BETA MATERIALS FOR MICROSOFT CERTIFIED TRAINER PREPARATION PURPOSES ONLY Module 2: Using Web Controls Web controls

Ngày đăng: 27/10/2013, 07:15

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan