Creating Web Applications with ASP.NET

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:20

lượt xem

Creating Web Applications with ASP.NET

Mô tả tài liệu
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Tạo ứng dụng Web với ASP.NET ứng dụng A Web có sử dụng ASP.NET thường bao gồm một hoặc nhiều trang Web ASP.NET hình thức, các tập tin mã, và các file cấu hình.

Chủ đề:

Nội dung Text: Creating Web Applications with ASP.NET

  1. Creating Web Applications with ASP.NET A Web application that uses ASP.NET typically consists of one or more ASP.NET pages or Web forms, code files, and configuration files. A Web form is held in an .aspx file, which is essentially an HTML file with some Microsoft .NET–specific tags. An .aspx file defines the layout and appearance of a page. Each .aspx file often has an associated code file containing the application logic for the components in the .aspx file, such as event handlers and utility methods. A tag, or directive, at the start of each .aspx file specifies the name and location of the corresponding code file. ASP.NET also supports application-level events, which are defined in Global.asax files. Each Web application can also have a configuration file called Web.config. This file, which is in XML format, contains information regarding security, cache management, page compilation, and so on. Building an ASP.NET Application In the following exercise, you will build a simple ASP.NET application that uses Server controls to gather input from the user about the details of the employees of a fictitious software company. The application will show you the structure of a typical Web application. NOTE You do not need to have IIS running on your computer in order to develop Web applications. Visual Studio 2005 includes its own Development Web server. When you build and run a Web application, by default Visual Studio 2005 will run the application using this server. However, you should still use IIS for hosting production Web applications after you have finished developing and testing them. Create the Web application 1. Start Microsoft Visual Studio 2005, if it is not already running. 2. On the File menu, point to New and then click Web Site. The New Web Site dialog box appears. 3. Click the ASP.NET Web Site template. Select File System in the Location drop- down list box, and type C:\Documents and Settings\YourName\My Documents\Microsoft Press\Visual CSharp Step by Step\Chapter 25\HonestJohn where YourName is your Windows login name. Set the Language to Visual C#, and then click OK.
  2. NOTE Setting the Location to FileSystem uses the Development Web server provided with Visual Studio 2005. You can use IIS by setting the Location to HTTP and specifying the URL of the Web Site you want to create rather than a file name. An application is created consisting of a Web Folder called App_Data, and a Web form called Default.aspx. The HTML code for the default page appears in the Source View window. 4. In the Solution Explorer select the Default.aspx file. In the Properties window, change the File Name property of Default.aspx to EmployeeForm.aspx. 5. Click the Design button at the bottom of the form to display the Design View of the form. The Design View window is currently empty. In the Design View window, you can drag controls onto the Web form from the Toolbox, and Visual Studio 2005 will generate the appropriate HTML for you. This is the HTML that you see when you view the form in the Source View window. You can also edit the HTML directly if you want. In the next exercise, you will define a style to be used by the form and add controls to the form to make it functional. Using a style enables you to ensure that all controls on the form share a common look and feel (such as color and font), as well as setting items such as a background image of the form. Lay out the Web form 1. Click the form in the Design View window. In the Properties window, change the Title property of the DOCUMENT object to Employee Information. The value you specify for the Title property appears in the title bar of the Web Browser when you run the Web application. 2. Select the Style property and click the ellipses button. The Style Builder dialog box opens. This dialog box allows you to create a style for the form. (A style specifies the default font, color, layout, and other attributes for the Web form and its controls.)
  3. 3. In the Font Name section, verify that the Family option is selected, and then click the ellipses button on the right side. In the Font Picker dialog box that opens, select Arial in the Installed Fonts list, and then click the >> button to add it to the Selected Fonts list. Click OK to return to the Style Builder dialog box. 4. In the Color drop-down list, select Blue. 5. In the left pane of the dialog box, click Background. The Background page is displayed. Select the Transparent check box. 6. Using Windows Explorer, copy the file \Microsoft Press\Visual CSharp Step By Step\Chapter 25\computer.bmp in your My Documents folder to the \Microsoft Press\Visual CSharp Step By Step\Chapter 25\HonestJohn folder. 7. Return to the Style Builder dialog box in the Visual Studio 2005 programming environment. In the Image text box, type computer.bmp. Click OK. The Web form will contain a background image of a computer. 8. Open the Toolbox and ensure that the Standard category is expanded. The Toolbox contains controls that you can drop onto ASP.NET forms. These controls are similar, in many cases, to the controls you have been using to build Windows forms. The difference is that these controls have been designed to operate in an HTML environment, and they are rendered using HTML at run time. 9. From the Toolbox, drag and drop four Label controls and three TextBox controls onto the Web form. Notice how the controls pick up the font and color specified by the Web form's style. NOTE The controls will be automatically positioned using a left-to-right flow layout in the Design View window. Do not worry about their location just yet as you will move them after setting their properties. NOTE As well as using a Label control, you can also type text directly onto a Web page. However, you cannot format this text so easily, set properties, or apply Themes to it. If you are building a Web site that has to support different languages (such as French or German), use Label controls as you can more easily localize the text they display by using Resource files. For more information, see “Resources in Applications” in the Microsoft Visual Studio 2005 Documentation. 10. Using the Properties window, set the properties of these controls to the values shown in the following table. Control Property Value
  4. Control Property Value Label1 Font Bold (expand the Font property) True Font Name Arial Black Font Size X-Large Text Honest John Software Developers Height 36px Width 630px Label2 Text First Name Label3 Text Last Name Label4 Text Employee Id TextBox1 Height 24px Width 230px (ID) firstName TextBox2 Height 24px Width 230px (ID) lastName TextBox3 Height 24px Width 100px (ID) employeeID 11. In the Design View window, select all four labels and all three text boxes (click Label1, and the click the remaining controls while holding down the Shift key). 12. In the Layout menu, point to Position and then click Absolute. This setting enables you to drag the controls to an absolute position on the form rather than Visual Studio 2005 laying them out automatically. 13. Move the labels and text boxes to the positions shown on the form in the following graphic: TIP You can align and space controls by using the commands on the Format menu. To align a set of controls, select them all and then, on the Format menu, click Align and select the appropriate alignment (Lefts, Centers, Rights, Tops, Middles, Bottoms). Similarly, you can space controls by selecting them and then by using the Horizontal Spacing or Vertical Spacing commands on the Format menu.
  5. 14. Click the Source button at the bottom of the form to display the HTML representation of the form and controls in the Source View window. The HTML should look like similar to the following code (the positions of the controls might vary slightly on your form): Employee Information   
  6. position: absolute; top: 101px" Height="24px" Width="230px"> 15. Return to the Design View window. 16. In the Layout menu, point to Position and click Auto-position Options. In the Options dialog box, expand the HTML Designer node of the tree view control if it is not already expanded and click CSS Positioning. In the right-hand pane of the dialog box, check “Change positioning to the following for controls added by using the Toolbox, paste, or drag and drop”, and select “Absolutely positioned” from the drop-down menu: This action allows all future controls that you add to the form to be placed wherever you drag them after adding them to the form; you do not need enable absolute positioning for each one. 17. Add another Label control and four RadioButton controls to the Web form. Set the properties of these controls to the values listed in the following table. Control Property Value Label5 Text Position RadioButton1 Text Worker TextAlign Left GroupName positionGroup Checked True (ID) workerButton RadioButton2 Text Boss TextAlign Left GroupName positionGroup Checked False (ID) bossButton RadioButton3 Text Vice President
  7. Control Property Value TextAlign Left GroupName positionGroup Checked False (ID) vpButton RadioButton4 Text President TextAlign Left GroupName positionGroup Checked False (ID) presidentButton 18. The GroupName property determines how a set of radio buttons are grouped. All buttons with the same value for GroupName are in the same group—only one can be selected at a time. 19. Position these controls so that your Web form looks like the following graphic: 20. Add another Label control and a DropDownList control to the Web form. Set their properties to the values shown in the following table. Control Property Value Label6 Text Role DropDownList1 Width 230px (ID) positionRole 21. The positionRole drop-down list will display the different positions that an employee can have within the company. This list will vary according to the position of the employee in the company. You will write code to populate this list dynamically. 22. Position these controls so that the form looks like the following graphic: 23. Add two Button controls and another Label control to the form. Set their properties to the values shown in the following table. Control Property Value Button1 Text Save
  8. Control Property Value (ID) saveButton Button2 Text Clear (ID) clearButton Label7 Text leave blank Height 48px Width 680px (ID) infoLabel 24. Position the controls so that the form looks like the following graphic: You will write event handlers for these buttons in a later exercise. The Save button will collate the information entered by the user and display it in the InfoLabel control at the bottom of the form. The Clear button will clear the text boxes and set other controls to their default values. Test the Web form 1. On the Debug menu, click Start Debugging. Visual Studio 2005 builds the application, the ASP.NET Development Server starts, and then Internet Explorer starts and displays the form. NOTE The first time you run a Web application by using the Start Debugging command, you will be prompted with a message box stating that debugging is not enabled. You can either select “Run without debugging”, or select “Modify the Web.config file to enable debugging” if you really want to run in debug mode. Running in debug mode is useful initially because you can set breakpoints and single step through the code using the debugger, as described in Chapter 3, “Writing Methods and Applying Scope.” However, enabling debugging will slow the application down and should be disabled before deploying the application to a production Web site. You can do this by editing the Web.config file and removing the following line: 2. Enter some information for a fictitious employee. Test the radio buttons to verify that they are all mutually exclusive. Click the drop-down arrow in the Role list; the list will be empty. Click Save and Clear.
  9. 3. Close Internet Explorer and return to the Visual Studio 2005 programming environment. Deploying a Web Site to IIS A new feature added to Visual Studio 2005 is the Copy Web Site command on the Website menu, for copying a Web site from one location to another. You can use this feature to quickly deploy a Web site built and tested using the ASP.NET Development Server to a production IIS site. (You should create a new Web site, or an empty virtual directory by using the Internet Information Services management console first.) Connect to the virtual directory on the production IIS site. You can then selectively copy individual files to or from the production Web site, or synchronize files between Web sites. For more information, see “Walkthrough: Copying a Web Site Using the Copy Web Site Tool” and “How to: Copy Web Site Files with the Copy Web Tool” in the Microsoft Visual Studio 2005 Documentation. Understanding Server Controls The Web Forms controls you added to the form are collectively known as Server controls. Server controls are similar to the standard HTML items that you can use on an ordinary Web page, except that they are more programmable. Most Server controls expose event handlers, methods, and properties that code running on the server can execute and modify dynamically at run time. In the following exercises, you will learn more about programming Server controls. Examine a Server control 1. In the Visual Studio 2005 programming environment, display EmployeeForm.aspx in the Source View window. 2. Examine the HTML code for the form. Notice that it contains the definitions for each of the controls. Look at the definition of the first Label control in more detail (the code won't look exactly like the following listing, which has been laid out to make it easier to read): 3.
  10. 8. Font-Size="X-Large" Height="36px" Width="630px"> There are a couple of things to observe. First, look at the type of the control: asp:Label. All Web forms controls live in the “asp” namespace because this is the way they are defined by Microsoft. The second noteworthy item is the runat="server" attribute. This attribute indicates that the control can be accessed programmatically by code running on the Web server. This code can query and change the values of any of the properties of this control (for example, change its text). NOTE All controls must be properly ended with a matching tag, where Control is the type of the control, such as Label as shown in the example. 9. Return to the Design View window. HTML Controls ASP.NET also supports HTML controls. If you expand the HTML category in the Toolbox, you are presented with a list of controls. These are the controls that Microsoft supplied with the original Active Server Pages model. They are provided so that you can port existing ASP pages into ASP.NET more easily. However, if you are building an application from scratch, you should use the Standard Web Forms controls instead. HTML controls also have a runat attribute, allowing you to specify where event handling code should be executed for these controls. Unlike Web Forms controls, the default location for HTML controls to execute code is in the browser rather than on the server— assuming that the user's browser supports this functionality. The EmployeeForm.aspx page requires several event handlers: a set of handlers to populate the PositionRole drop-down list when the user selects a position (Worker, Boss, Vice President, President); another handler to save the information entered when the user clicks the Save button; and a final handler to clear the form when the user clicks the Clear button. You will write these handlers in the next exercise. Write event handlers 1. In the Solution Explorer, expand the file EmployeeForm.aspx. The file EmployeeForms.aspx.cs will appear. This is the file that will actually contain the C# code for the event handlers that you write. This file is known as a code-behind file. This feature of ASP.NET enables you to separate the C# code
  11. from the the display logic for a Web application (you can actually write C# code and event handlers in the EmployeeForm.aspx file by using the Source View window, but this approach is not recommended). 2. Display the HTML code for EmployeeForm.aspx in the Source View window. Examine the first line in this file. It looks like this:
  12. 12. Add the following statement to the Page_Load method: 13. if (!IsPostBack) 14. { 15. initPositionRole(); } This block of code will cause the positionRole drop-down list to be populated when the form appears in the user's browser. However, it is important to understand that the Page_Load method runs every time the Web server sends the form to the user's browser, not just the first time. For example, when the user clicks a button the form can be sent back to the Web server for processing; the Web server then responds by sending the form back to the browser for displaying when the processing has completed. You don't necessarily want the initialization to be performed every time the page appears, as it is a waste of processing and can lead to performance problems if you are building a commercial Web site. You can determine whether the Page_Load method is running because this is the first time the page is being displayed by querying the IsPostBack property of the Web page. This property returns false the first time the page is displayed, and true if the page is being redisplayed because the user has clicked a control. In the code you added, you only call the initPositionRole method when the form is first displayed. 16. Switch to the EmployeeForm.aspx file, and change to Design View for the form. Select the workerButton radio button. In the Properties window, click the Events button. Double-click the CheckedChanged event. This event occurs when the user clicks the radio button and its value changes.Visual Studio 2005 generates the method workerButton_CheckedChanged to handle this event. 17. In the workerButton_CheckedChanged event method, add the following statement: initPositionRole(); Remember that the default values for the positionRole drop-down list are those for a worker, so the same method can be reused to initialize the list. 18. Switch to EmployeeForm.aspx in the Design View window. Select the bossButton radio button, and use the Properties window to create an event method called bossButton_CheckedChanged for the CheckedChanged event. When the form is displayed in Code and Text Editor window, type the following statements in the BossChecked method: 19. positionRole.Items.Clear(); 20. positionRole.Enabled = true; 21. positionRole.Items.Add("General Manager"); positionRole.Items.Add("Project Manager");
  13. These are the roles that a manager can fulfill. 22. Switch to EmployeeForm.aspx in the Design View window and create an event handler for the CheckedChanged event for the vpButton (Vice president) radio button. Add the following statements to the event method: 23. positionRole.Items.Clear(); 24. positionRole.Enabled = true; 25. positionRole.Items.Add("VP Sales"); 26. positionRole.Items.Add("VP Marketing"); 27. positionRole.Items.Add("VP Production"); positionRole.Items.Add("VP Human Resources"); 28. Create a final event handler for the CheckedChanged event for the President radio button. Add the following code to the event method: 29. positionRole.Items.Clear(); positionRole.Enabled = false; Roles do not apply to the president of the company, so the drop-down list is disabled. 30. Create an event handler for the Click event of the Save button. The method would usually be used to save the information to a database, but to keep this application simple, the method will just echo some of the data in the InfoLabel control instead. Add the following statements to the saveButton_Click method: 31. string position = ""; 32. 33. if (workerButton.Checked) 34. position = "Worker"; 35. if (bossButton.Checked) 36. position = "Manager"; 37. if (vpButton.Checked) 38. position = "Vice President"; 39. if (presidentButton.Checked) 40. position = "President"; 41. 42. infoLabel.Text = "Employee:&nbsp" + firstName.Text + "&nbsp" + 43. lastName.Text + "&nbsp&nbsp&nbsp&nbspId&nbsp" + 44. employeeID.Text + "&nbsp&nbsp&nbsp&nbspPosition&nbsp" + position; The &nbsp character is a non-breaking space in HTML; ordinary white-space characters after the first white-space character will normally be ignored by the browser.
  14. 45. Create an event method for the Click event of the Clear button. Add the following block of code to this method: 46. firstName.Text = ""; 47. lastName.Text = ""; 48. employeeID.Text = ""; 49. workerButton.Checked = true; 50. initPositionRole(); infoLabel.Text = ""; This code clears the information entered by the user and then resets the role to Worker (the default value). Test the Web form again 1. Run the Web form again. 2. Type in an employee's name and ID number (make them up). Click the Role drop- down list. The list of roles for a worker is displayed. 3. Change the position of your fictitious employee to Vice President, and then click the Role drop-down list box. Notice that the list has not changed and still displays the roles for a worker. The list hasn't changed because the CheckedChanged event for the Vice President radio button has not fired. 4. Close Internet Explorer and return to the Visual Studio 2005 programming environment. 5. Display EmployeeForm.aspx in the Design View window, and then select the worker-Button radio button. In the Properties window, set the AutoPostBack property to True. When the user clicks this radio button, the form will be sent back to the server for processing, the CheckedChanged event will fire, and the form can be updated to display the roles for this radio button. By default, the AutoPostBack property is set to False to avoid unnecessary network traffic. Set the AutoPostBack property to True for the other radio buttons: bossButton, vpButton, and presidentButton.
  15. TIP You can hold down the Shift key and select all four radio buttons, and then set properties for them all at the same time in the Properties window. 6. Run the Web form again. This time you will find that when you click the radio buttons, there is a slight flicker while the form is submitted to the server, the event handler runs, the drop- down list is populated, and the form is displayed again. 7. On the View menu in Internet Explorer, click Source to display the source of the HTML page being displayed in the browser. Notepad starts and displays the HTML source for the page. Notice that there is no mention of any “asp:” Server controls in this file and no C# code. Instead, the Server controls and their contents have been converted to the equivalent HTML controls (and some JavaScript). This is one of the basic features of the Server controls—you access them programmatically like ordinary .NET Framework objects, with methods, properties, and events. When they are rendered by the Web server, they are converted into HTML, allowing you to use any HTML compliant browser to view ASP.NET Web forms at run time. When you have finished examining the file, close Notepad. 8. Click Save. The InfoLabel control displays the details of the new employee. If you examine the source, you will see that the HTML for the InfoLabel control (rendered as an HTML span with an ID of “InfoLabel”) contains this text. 9. Click Clear. The form resets to its default values. 10. Close Internet Explorer and return to the Visual Studio 2005 programming environment. Event Processing and Round-Trips Server controls are undoubtedly a very powerful feature of ASP.NET, but they come with a price. You should remember that although events are raised by the Web client, the event code is executed on the Web server and that each time an event is raised, an HTTP request (or postback) is sent over the network to the Web server. The task of the Web server is to process this request and send a reply containing an HTML page to be
  16. displayed. In the case of many events, this page will be the same as the one that issued the original request. However, the Web server also needs to know what other data the user has entered on the page so that when it generates the HTML response, it can preserve these values in the display. (If the Web server only sent back the HTML that composed the original page, any data entered by the user would disappear.) If you look at the HTML source of a page generated by a Web form, you will notice a hidden input field in the form. The example shown previously had this hidden field: This information is the content of the controls, or view state, in an encoded form. It is sent to the Web server whenever any event causes a postback. The Web server will use this information to repopulate the fields on the page when the HTML response is generated. All of this data has an impact on scalability. The more controls you have on a form, the more state information has to be passed between the browser and Web server during the postback processing, and the more events you use, the more frequently this will happen. In general, to reduce network overhead, you should keep your Web forms relatively simple and avoid excessive use of server events, and be selective with view state to avoid sending unnecessary information across the network. You can disable the view state for a control by setting the EnableViewState property of the control to False (the default setting is True). Creating and Using a Theme When you first created the Web site, you defined a style for the form. This style determined the default font and color for controls on the form, and could also be used to specify default values for other attributes, such as the way in which lists are formatted and numbered (click the Lists tab in the Style Builder dialog box if you want to experiment with list formatting). However, a style defined in this way only applies to a single form. Commercial Web sites typically contains tens, or maybe hundreds of forms. Keeping all of these forms consistently formatted can be a time-consuming task (imagine if the company you work for decided to change the font on all of its Web pages, how many forms would you need to update and rebuild). This is where Themes can be very
  17. useful. A Theme is a set of properties, styles, and images that you can apply to the controls on a page, or globally across all pages in a Web site. NOTE If you are familiar with cascading style sheets (.css files), then the concept of Themes might be familiar to you. However, there are some differences between cascading style sheets and Themes. In particular, Themes do not cascade in the same way as cascading style sheets, and properties defined in a Theme applied to a control always override any local property values defined for the control. Defining a Theme A Theme comprises a set of skin files located in a named subfolder in the App_Themes folder for a Web site. A skin file is a text file that has the file extension “.skin”. Each skin file specifies the default properties for a particular type of control using syntax very similar to that which is displayed when you view a Web form in the Source View window. For example, the following skin file specifies the default properties for TextBox and Label controls: You can specify many properties of a control in a skin file, but not all of them. For example, you cannot specify a value for the AutoPostBack property. Additionally, you cannot create skin files for every type of control, but most commonly used controls can be configured in this way. Applying a Theme After you have created a set of skin files for a Theme, you can apply the Theme to a page by modifying the @Page attribute that occurs at the start of the page when displayed in the Source View window. For example, if the skin files for a Theme are located in the App_Themes\BlueTheme folder under the Web site, you can apply the Theme to a page like this: If you want to apply the Theme to all pages in the Web site, you can modify the Web.config file and specify the Theme in the pages element, like this:
  18. If you modify the definition of a Theme, all controls and pages that use the Theme will pick up the changes automatically when they are next displayed. In the final set of exercises in this chapter, you will create a Theme for the Honest John Web site, and apply this Theme to all pages in the Web site. Create a new theme 1. In the Visual Studio 2005 programming environment, open the Honest John Web site if it is not already open. 2. In the Solution Explorer, right-click the Honest John project folder. Point to Add ASP.NET Folder, and then click Theme. A new folder called App_Themes is added to the project, and a sub-folder is created called Theme1. 3. Change the name of the Theme1 folder to HJTheme. 4. In the Solution Explorer, right-click the HJTheme folder and then click Add New Item. The Add New Item dialog box appears displaying the types of file that can be stored in a Themes folder. 5. Click the Skin File template, and type for the name. Click Add. The skin file is added to the HJTheme folder, and the file is displayed in the Code and Text Editor window. 6. Add the following lines to the end of the file in the Code and Text Editor window (this file contains a comment with some very brief instructions): 7. 8. 9. 10. This simple set of properties displays TextBox, Button, and DropDownListBox controls as white text on a red background, and Label and RadioButton controls as red text on a white background. The text on Label and Button controls is displayed using the bold font version of the current font.
  19. IMPORTANT The skin file editor is very basic and does not provide any Intellisense to help you. If you make a mistake in this file, the application will run, but entries in this file might be ignored. When you run the application later, if any of the controls do not appear as expected, ensure you have not mistyped anything in this file. As mentioned previously, there are at least two ways you can apply a Theme to a web form: you can set the @Page attribute for each page, or you can specify the Theme globally across all pages by using an Web configuration file. You are going to use the latter approach in the next exercise. Using this mechanism will cause all new pages that you add to the site to automatically apply the same Theme. Create a Web configuration file and apply the theme 1. In the Solution Explorer, right-click the Honest John project and click Add New Item. The Add New Item dialog box appears displaying the types of file that you can add to a Web site. 2. Click the Web Configuration File template, ensure the name is set to Web.config, and click Add. The file Web.config is added to the project and appears in the Code and Text Editor window. 3. Scroll to the end of the Web.config file, and insert a new line immediately above the line. Type the following entry in this new line: 4. On the Debug menu, click Start Without Debugging. TIP If Internet Explorer displays a list of files rather than the Web form, close Internet Explorer and return to Visual Studio 2005. In the Solution Explorer, right-click EmployeeForm.aspx and click Set As Start Page. Then run the Web application again. 5. Internet Explorer appears displaying the Web form. Verify that the style of the controls on the form have changed as expected, although any text in the text boxes might be a little hard to read (you will fix this shortly). Close Internet Explorer when you have finished.
  20. 6. In Visual Studio 2005, display the file in the Code and Text Editor window. Modify the element defining the appearance of TextBox and DropDownList controls, as follows: 7. 8. ... 9. Run the form again. Notice how the style of all the TextBox controls (First Name, Last Name, and Employee Id) and the DropDownList (Role) has changed, and is easier to read. Close Internet Explorer when you have finished. • If you want to continue to the next chapter Keep Visual Studio 2005 running and turn to Chapter 26. • If you want to exit Visual Studio 2005 for now On the File menu, click Exit. If you see a Save dialog box, click Yes.
Đồng bộ tài khoản