1. Trang chủ
  2. » Công Nghệ Thông Tin

mcts 70-562 Microsoft .NET Framework 3.5, ASP.NET Application Development phần 2 docx

108 284 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 108
Dung lượng 1,87 MB

Nội dung

Lesson 2: Exploring Common Server Controls CHAPTER 2 79 FIGURE 2-16 Defining properties of the RadioButton control on a Web page Quick Check 1. What are the two types of Web server Button controls that can be created? 2. How do you create a TextBox for retrieving a password from a user? 3. How do you make a CheckBox cause immediate PostBack to the server? Quick Check Answers 1. The two types of Web server Button controls are submit and command buttons. 2. You can mask the user’s entered password by setting the TextMode property of the TextBox control to Password. 3. You can force an immediate PostBack for a CheckBox control by setting its Auto- PostBack property to true. Lab Working with Web Server Controls In this lab, you work with the Web server controls that are defi ned in this chapter. If you encounter a problem completing an exercise, the completed projects are available on the companion CD in the Code folder. Quick Check 1 . What are the two types of Web server Button controls that can be created? 2 . How do you create a TextBox for retrieving a password from a user? TextBox for retrieving a password from a user?TextBox 3 . How do you make a CheckBox cause immediate PostBack to the server? CheckBox cause immediate PostBack to the server?CheckBox Quick Check Answers 1 . The two types of Web server Button controls are submit and command buttons. 2 . You can mask the user’s entered password by setting the TextMode property of the TextBox control to TextBox control to TextBox Password . 3 . You can force an immediate PostBack for a CheckBox control by setting its CheckBox control by setting its CheckBox Auto- PostBack property to PostBack property to PostBack true . 1 2 3 1 2 3 80 CHAPTER 2 Adding and Configuring Server Controls ExErcisE 1 Adding Controls to the Web Page In this exercise, you add Web server controls to a Web page. 1. Open Visual Studio and create a new Web site called WebServerControls. 2. Open the Default.aspx Web page in Design view. 3. Drag a Label, CheckBox, TextBox, three RadioButtons, and a Button control onto the Web page. Change the Text properties of these controls to match Figure 2-17. In addition, name these items LabelInformation, CheckBoxAdmin, TextBoxUser- Name, RadioButton1, RadioButton2, RadioButton3, and ButtonSave, respectively. Also, set the GroupName for the radio buttons to ApplicationRole. FIGURE 2-17 Drag Web server controls onto the page as shown 4. Right-click the Web page and select View Code to open the code-behind page. Notice that no additional code was added to the code-behind page. 5. Run the Web application. Click the Button, CheckBox, and RadioButton controls. Ob- serve the behavior of these controls. Notice that the Button is the only control that performs a PostBack to the server. Also notice that the RadioButton controls are not mutually exclusive. 6. Open the page in Design view. Select the TextBox control and set its MaxLength prop- erty to 12 to restrict user input. 7. Run the page and type in the TextBox control. Notice that you cannot type more than 12 characters into the control. Lesson 2: Exploring Common Server Controls CHAPTER 2 81 8. Double-click the CheckBox control to add the CheckedChanged event handler. Add code to replace its Text property based on whether or not the user has selected the check box. Your code should look like the following: 'VB Protected Sub CheckBoxAdmin_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CheckBoxAdmin.CheckedChanged If CheckBoxAdmin.Checked Then CheckBoxAdmin.Text = "System Administrator" Else CheckBoxAdmin.Text = "Check to set as system administrator" End If End Sub //C# protected void CheckBoxAdmin_CheckedChanged(object sender, EventArgs e) { if (CheckBoxAdmin.Checked) { CheckBoxAdmin.Text = "System Administrator"; } else { CheckBoxAdmin.Text = "Check to set as system administrator"; } } 9. Run the page. Notice that changing the CheckBox control has no effect. Click Save and notice that the text changes as the button causes a PostBack. Return to the page and set the AutoPostBack property of the CheckBox control to true. Rerun the page and select the CheckBox to see the results. 10. To make the RadioButton controls mutually exclusive, these controls must have the same GroupName property setting. Assign ApplicationRole to the GroupName prop- erty of all three RadioButton controls. 11. Run the page and select each of the radio buttons. Notice that they are now mutually exclusive. 12. Open the page in Design view. Double-click the Button control to add the button’s Click event handler to your code-behind fi le. Add the following code to populate the Label indicating the page’s data has been saved: 'VB Protected Sub ButtonSave_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ButtonSave.Click 'VB Protected Sub CheckBoxAdmin_CheckedChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles CheckBoxAdmin.CheckedChanged If CheckBoxAdmin.Checked Then CheckBoxAdmin.Text = "System Administrator" Else CheckBoxAdmin.Text = "Check to set as system administrator" End If End Sub //C# protected void CheckBoxAdmin_CheckedChanged(object sender, EventArgs e) { if (CheckBoxAdmin.Checked) { CheckBoxAdmin.Text = "System Administrator"; } else { CheckBoxAdmin.Text = "Check to set as system administrator"; } } 'VB Protected Sub ButtonSave_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles ButtonSave.Click 82 CHAPTER 2 Adding and Confi guring Server Controls LabelInformation.Text = "User information saved." End Sub //C# protected void ButtonSave_Click(object sender, EventArgs e) { LabelInformation.Text = "User information saved."; } 13. Run the page, click Save, and notice the results. Lesson Summary n The Label control displays text at a specifi c location on the Web page using the prop- erties that have been assigned to the Label control. n The TextBox control collects text from the user. n The Button control displays a push button on the Web page that can be clicked to trig- ger a PostBack to the Web server. n The CheckBox control gives the user the ability to select between true and false. n The RadioButton control gives the user the ability to select between mutually exclusive RadioButton controls in a group. Lesson Review You can use the following questions to test your knowledge of the information in Lesson 2, “Exploring Common Server Controls.” The questions are also available on the companion CD if you prefer to review them in electronic form. NOTE ANSWERS Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. 1. If you want multiple RadioButton controls to be mutually exclusive, what property must you set? A. Exclusive B. MutuallyExclusive C. Grouped D. GroupName LabelInformation.Text = "User information saved." End Sub //C# protected void ButtonSave_Click(object sender, EventArgs e) { LabelInformation.Text = "User information saved."; } NOTE ANSWERS Answers to these questions and explanations of why each answer choice is right or wrong are located in the “Answers” section at the end of the book. Lesson 2: Exploring Common Server Controls CHAPTER 2 83 2. You are creating a Web page that has several related buttons, such as fast forward, reverse, play, stop, and pause. You want to create a single event handler that processes the PostBack from these Button controls. Other than the normal submit button, what type of button can you create as a solution? A. OneToMany B. Command C. Reset D. ManyToOne 3. In Design view, what is the simplest way to create an event handler for the default event of a server control? A. Open the code-behind page and write the code. B. Right-click the control and select Create Handler. C. Drag an event handler from the Toolbox to the desired control. D. Double-click the control. 84 CHAPTER 2 Adding and Confi guring Server Controls Lesson 3: Exploring Specialized Server Controls It was not long ago when creating something as basic as a calendar on a Web page was a time-consuming task involving the creation of HTML tables with hyperlinks on each date. You also had to create JavaScript to process the selection of a date, and more. With ASP.NET, com- mon tasks such as creating a calendar involve simply dragging and dropping a feature-rich control on your Web page. The previous lesson covered some of the more basic controls used to build Web pages. There are, of course, many more controls available for use. This lesson covers the more spe- cialized Web server controls. These are controls that go beyond those basic controls but are not covered elsewhere in the chapter. After this lesson, you will be able to: n Use the following Web server controls: n Literal n Table, TableRow, and TableCell n Image n ImageButton n ImageMap n Calendar n FileUpload n Panel n MultiView n View n Wizard Estimated lesson time: 60 minutes The Literal Control The Literal control is similar to the Label control in that both controls are used to display static text on a Web page. The Literal control does not inherit from WebControl, as shown in the Literal control’s object model in Figure 2-18. The Literal control does not provide substantial functionality and does not add any HTML elements to the Web page, whereas the Label is rendered as a <span> tag. This means that the Literal control does not have a style property, and you therefore cannot apply styles to its content. After this lesson, you will be able to: n Use the following Web server controls: n Literal n Table , TableRow , and TableRow, and TableRow TableCell n Image n ImageButton n ImageMap n Calendar n FileUpload n Panel n MultiView n View n Wizard Estimated lesson time: 60 minutes Estimated lesson time: 60 minutes Lesson 3: Exploring Specialized Server Controls CHAPTER 2 85 FIGURE 2-18 The Literal control object model The Literal control is useful when you need to add text to the output of the page dynami- cally (from the server) but do not want to use a Label. If your text is static, you can simply add it to the markup of the page (you do not need a Label or a Literal control). The Literal control contains the Mode property, which is used to specify particular handling of the content of the Text property. The modes available and their descriptions are shown in Table 2-4. TABLE 2-4 The Literal Control’s Mode Property MODE DESCRIPTION PassThrough The Text content is rendered as is. This includes HTML markup and script. These items are output to the page and processed by the browser as HTML and script. Encode The Text content is HTML-encoded; that is, any HTML markup or script is actually treated like text and not HTML or script. Transform The Text content is converted to match the markup language of the requesting browser, such as HTML, Extensible Hypertext Markup Language (XHTML), Wireless Markup Language (WML), or Compact Hy- pertext Markup Language (cHTML). If the markup language is HTML or XHTML, the content is passed through to the browser. For other markup languages, invalid tags are removed. 86 CHAPTER 2 Adding and Configuring Server Controls As an example, consider a Web page with three Literal controls, one for each Mode prop- erty setting. Suppose the following code is added to the code-behind page to demonstrate the use of the Literal control and the effect of the Mode property: 'VB Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load Literal1.Text = _ "This is an <font size=7>example</font><script>alert(""Hi"");</script>" Literal2.Text = _ "This is an <font size=7>example</font><script>alert(""Hi"");</script>" Literal3.Text = _ "This is an <font size=7>example<script>alert(""Hi"");</script>" Literal1.Mode = LiteralMode.Encode Literal2.Mode = LiteralMode.PassThrough Literal3.Mode = LiteralMode.Transform End Sub //C# protected void Page_Load(object sender, EventArgs e) { Literal1.Text = @"This is an <font size=7>example</font><script>alert(""Hi"");</script>"; Literal2.Text = @"This is an <font size=7>example</font><script>alert(""Hi"");</script>"; Literal3.Text = @"This is an <font size=7>example</font><script>alert(""Hi"");</script>"; Literal1.Mode = LiteralMode.Encode; Literal2.Mode = LiteralMode.PassThrough; Literal3.Mode = LiteralMode.Transform; } Figure 2-19 shows the rendered output of the Literal control when the Web page is dis- played. The alert message was displayed twice: once for Transform and once for PassThrough. Note that this is a security risk if you are setting the Text property of the Literal control dynamically from user input. However, the encoded version of the Literal control encodes the HTML and script and displays it to the browser window. Lesson 3: Exploring Specialized Server Controls CHAPTER 2 87 FIGURE 2-19 Literal controls rendered using different Mode settings The Table, TableRow, and TableCell Controls Web developers have been using tables to format information displayed on Web pages since the fi rst HTML pages. Tables are useful for tabular data, but they can also help with the layout of graphics and controls on a form. The concept of columns and rows is a powerful layout technique for Web pages. HTML provides the <table> tag for defi ning a table, the <tr> tag for creating a row, and the <td> tag for defi ning a column in the row. Web developers should be very familiar with these tags. ASP.NET provides the Table control for creating and managing tables without these tags. Like its HTML counterpart, the Table control can be used to display static informa- tion on a page. However, the Table control’s real power comes from the ability to program- matically add TableRow and TableCell controls from your code at run time. If you only need to display static information, consider using the HTML tags instead. EXAM TIP There is also an HtmlTable control. It can be created from the HTML <table> tag by adding the runat=”server” attribute to the tag and assigning an ID to the tag. However, the Table control is easier to use because it provides a programming model that is consistent with the TableRow and TableCell controls. 88 CHAPTER 2 Adding and Configuring Server Controls Again, the Table control is the right choice when you need to programmatically add rows and cells to a table at run time. The rows are added using the TableRow control and the cells are added using the TableCell control. You add these rows and cells in a similar manner as you would dynamically create other controls on a page. This also means the same rules apply to these dynamically created controls. That is, for them to be available at PostBack they need to be re-created when the page posts back to the server. Your page might only be for display or it might be simple enough to manage. In either case you should be fine to use a Table control. However, if your needs are more complicated, you have a lot of data, and you need it to sur- vive PostBack, consider using the Repeater, DataList, or GridView controls. The Table control is also very useful for control developers who use a table as part of a custom control. The Table control provides an object model that is consistent with other Web controls. Figure 2-20 shows the Table control’s object model. FIGURE 2-20 The Table control’s object mode Notice that the Table control contains a Rows collection property (shown as a collection association in Figure 2-20). This property is a collection of TableRow controls. It is used to add and access the rows of your table. The TableRow control contains a Cells collection property (also shown as a collection association). This property represents a collection of TableCell controls. These are the actual cells (or columns) within the given row. The Table, TableRow, and TableCell all inherit from the WebControl class. This class provides base properties such as Font, BackColor, and ForeColor. If you set these properties at the Table level, you can override them in TableRow instances, and in turn, the TableRow settings can be overridden in the TableCell instances. [...]... DateTime (20 09, 2, 1) Calendar1.VisibleDate = Calendar1.TodaysDate End Sub Private Function GetSchedule() As Hashtable Dim schedule As New Hashtable() schedule( "2/ 9 /20 09") = "Vacation Day" schedule( "2/ 18 /20 09") = "Budget planning meeting @ 3:00pm" schedule( "2/ 24 /20 09") = "Dinner plans with friends @ 7:00pm" schedule( "2/ 27 /20 09") = "Travel Day" schedule("3/5 /20 09") = "Conf call @ 1:00pm" schedule("3/10 /20 09")... CHAPTER 2 Adding and Configuring Server Controls Calendar1.TodaysDate = new DateTime (20 09, 2, 1); Calendar1.VisibleDate = Calendar1.TodaysDate; } private Hashtable GetSchedule() { Hashtable schedule = new Hashtable(); schedule[ "2/ 9 /20 09"] = "Vacation Day"; schedule[ "2/ 18 /20 09"] = "Budget planning meeting @ 3:00pm"; schedule[ "2/ 24 /20 09"] = "Dinner plans with friends @ 7:00pm"; schedule[ "2/ 27 /20 09"] =... objects also have their BorderWidth set to 1, which causes each TableCell to be outlined as well When the Web page is displayed, it will look like the page shown in Figure 2- 22 90 CHAPTER 2 Adding and Configuring Server Controls Figure 2- 22 A Web page showing the result of dynamically creating TableRow and TableCell controls The Image Control The Image control can be used to display an image on a Web page... the ASP.NET source: 1 12 CHAPTER 2 Adding... ImageMapEventArgs contains the PostBackValue Inside the click event, the PostBackValue is placed into the Text property of the Label control Figure 2- 28 shows the page after the image has been clicked 1 00 CHAPTER 2 Adding and Configuring Server Controls Figure 2- 28  The rendered ImageMap displaying the PostBackValue message in the Label after the image was clicked The Calendar Control The Calendar control... contains many additional properties that can be used to adjust the format and behavior of this control Table 2- 6 contains a list of the Calendar properties and their associated descriptions Lesson 3: Exploring Specialized Server Controls CHAPTER 2 101 Figure 2- 29  The Calendar control hierarchy Table 2- 6  Calendar Properties Property Caption The text that is rendered in the Calendar CaptionAlign The alignment... Figure 2- 21 shows this dialog box in action Figure 2- 21  The TableRow collection editor in Visual Studio The real power of the Table control, however, is being able to work with it from your code The following steps show how to dynamically add TableCell and TableRow objects to an existing Table control 1 Open a Visual Studio Web site or create a new one Open (or create) a Web page with which to work 2. .. "WhaleImageDescription.htm"; Image1.AlternateText = "This is a picture of a whale"; } Figure 2- 24 shows the rendered Web page This includes the alternate text displayed as a ToolTip Figure 2- 24  The rendered Image control displaying the AlternateText property as a ToolTip Lesson 3: Exploring Specialized Server Controls CHAPTER 2 93 The ImageButton Control The Image control does not have a Click event In situations... y-coordinates are retrieved and placed into the Lesson 3: Exploring Specialized Server Controls CHAPTER 2 95 AlternateText property, as shown in Figure 2- 26 In this example you can use this information to determine the area (or color) on which the user clicked and make a decision accordingly Figure 2- 26  The rendered ImageButton displaying the AlternateText message after the ImageButton was clicked The... The first HotSpot defined takes precedence over the last HotSpot defined The HotSpot object model is also shown in Figure 2- 27 The classes that inherit from the HotSpot are the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot Table 2- 5 contains a list of HotSpot properties Table 2- 5  HotSpot Properties Property Description AccessKey AlternateText The keyboard shortcut for a HotSpot You can place . is displayed, it will look like the page shown in Figure 2- 22. Lesson 3: Exploring Specialized Server Controls CHAPTER 2 91 FIGURE 2- 22 A Web page showing the result of dynamically creating. its CheckBox Auto- PostBack property to PostBack property to PostBack true . 1 2 3 1 2 3 80 CHAPTER 2 Adding and Configuring Server Controls ExErcisE 1 Adding Controls to the Web Page In. browser initiates a separate request for the image from the server. 92 CHAPTER 2 Adding and Configuring Server Controls FIGURE 2- 23 The Image control hierarchy The Image control’s primary property,

Ngày đăng: 12/08/2014, 20:22

TỪ KHÓA LIÊN QUAN