Tài liệu Creating Web Applications with ASP.NET doc

20 434 0
Tài liệu Creating Web Applications with ASP.NET doc

Đ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

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. 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. 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 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. 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): <%@ Page Language="C#" AutoEventWireup="true" CodeFile="EmployeeForm.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/ xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Employee Information</title> </head> <body style="background-image: url(computer.bmp); color: blue; font-family: Arial; background-color: transparent"> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Honest John Software Developers" style="z-index: 100; left: 96px; position: absolute; top: 24px" Font-Bold="True" Font- Names="Arial Black" Font-Size="X-Large" Height="36px" Width="630px"></asp:Label> <asp:Label ID="Label2" runat="server" Text="First Name" style="z-index: 101; left: 62px; position: absolute; top: 104px"></asp:Label> <asp:Label ID="Label3" runat="server" Text="Last Name" style="z-index: 102; left: 414px; position: absolute; top: 104px"></asp:Label> <asp:Label ID="Label4" runat="server" Text="Employee Id" style="z-index: 103; left: 62px; position: absolute; top: 167px"></asp:Label>&nbsp;&nbsp; <asp:TextBox ID="firstName" runat="server" style="z-index: 104; left: 156px; position: absolute; top: 101px" Height="24px" Width="230px"></asp:TextBox> <asp:TextBox ID="lastName" runat="server" style="z-index: 107; left: 507px; position: absolute; top: 101px" Height="24px" Width="230px"></asp:TextBox> <asp:TextBox ID="employeeID" runat="server" style="z-index: 106; left: 160px; position: absolute; top: 161px" Height="24px" Width="100px"></asp:TextBox> </div> </form> </body> </html> 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 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 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: <compilation debug="true"/> 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. 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. <asp:Label ID="Label1" runat="server" 4. Text="Honest John Software Developers" 5. style="z-index: 100; left: 96px; 6. position: absolute; top: 24px" 7. Font-Bold="True" Font-Names="Arial Black" 8. Font-Size="X-Large" Height="36px" Width="630px"> </asp:Label> 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 </asp:Control> 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 [...]... 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... of using statements Note that this file makes heavy use of the System .Web namespace and its sub-namespaces—this is where the ASP.NET classes reside Also, notice the code itself is in a class called _Default that descends from System .Web. UI.Page; this is the class from which all Web Forms descend Currently, it contains a single empty method called Page_Load This method runs when the page is displayed... 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 . 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. 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

Ngày đăng: 24/12/2013, 09:16

Từ khóa liên quan

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

Tài liệu liên quan