Lập trình ứng dụng nâng cao (phần 9) potx

50 356 0
Lập trình ứng dụng nâng cao (phần 9) potx

Đ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

382 | Chapter 17: Programming ASP.NET Applications Web Forms implement a programming model in which web pages are dynamically generated on a web server for delivery to a browser over the Internet. With Web Forms, you create an ASPX page with more or less static content consisting of HTML and web controls, as well as AJAX and Silverlight, and you write C# code to add additional dynamic content. The C# code runs on the server for the standard ASPX event handlers and on the client for the Silverlight event handlers (JavaScript is used for standard AJAX event handlers), and the data produced is integrated with the declared objects on your page to create an HTML page that is sent to the browser. You should pick up the following three critical points from the preceding paragraph and keep them in mind for this entire chapter: • Web pages can have both HTML and web controls (described later). • Processing may be done on the server or on the client, in managed code or in unmanaged code, or via a combination. • Typical ASP.NET controls produce standard HTML for the browser. Web Forms divide the user interface into two parts: the visual part or user interface (UI), and the logic that lies behind it. This is called code separation; and it is a good thing. From version 2.0 of ASP.NET, Visual Studio takes advantage of par- tial classes, allowing the code-separation page to be far simpler than it was in version 1.x. Because the code-separation and declarative pages are part of the same class, there is no longer a need to have protected variables to reference the controls of the page, and the designer can hide its initialization code in a separate file. The UI page for ASP.NET pages is stored in a file with the extension .aspx. When you run the form, the server generates HTML sent to the client browser. This code uses the rich Web Forms types found in the System.Web and System.Web.UI namespaces of the .NET FCL, and the System.Web.Extension namespace in Microsoft ASP.NET AJAX. With Visual Studio, Web Forms programming couldn’t be simpler: open a form, drag some controls onto it, and write the code to handle events. Presto! You’ve writ- ten a web application. On the other hand, even with Visual Studio, writing a robust and complete web application can be a daunting task. Web Forms offer a very rich UI; the number and complexity of web controls have greatly multiplied in recent years, and user expecta- tions about the look and feel of web applications have risen accordingly. In addition, web applications are inherently distributed. Typically, the client will not be in the same building as the server. For most web applications, you must take Web Forms Fundamentals | 383 network latency, bandwidth, and network server performance into account when creating the UI; a round trip from client to host might take a few seconds. To simplify this discussion, and to keep the focus on C#, we’ll ignore client-side processing for the rest of this chapter, and focus on server- side ASP.NET controls. Web Forms Events Web Forms are event-driven. An event represents the idea that “something happened” (see Chapter 12 for a full discussion of events). An event is generated (or raised) when the user clicks a button, or selects from a list- box, or otherwise interacts with the UI. Events can also be generated by the system starting or finishing work. For example, if you open a file for reading, the system raises an event when the file has been read into memory. The method that responds to the event is called the event handler. Event handlers are written in C#, and are associated with controls in the HTML page through control attributes. By convention, ASP.NET event handlers return void and take two parameters. The first parameter represents the object raising the event. The second, called the event argument, contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which doesn’t expose any properties. For some controls, the event argument might be of a type derived from EventArgs that can expose properties specific to that event type. In web applications, most events are typically handled on the server and, therefore, require a round trip. ASP.NET supports only a limited set of events, such as button clicks and text changes. These are events that the user might expect to cause a signif- icant change, as opposed to Windows events (such as mouse-over) that might happen many times during a single user-driven task. Postback versus nonpostback events Postback events are those that cause the form to be posted back to the server imme- diately. These include click-type events, such as the button Click event. In contrast, many events (typically change events) are considered nonpostback in that the form isn’t posted back to the server immediately. Instead, the control caches these events until the next time a postback event occurs. You can force controls with nonpostback events to behave in a post- back manner by setting their AutoPostBack property to true. 384 | Chapter 17: Programming ASP.NET Applications State A web application’s state is the current value of all the controls and variables for the current user in the current session. The Web is inherently a “stateless” environment. This means that every post to the server loses the state from previous posts, unless the developer takes great pains to preserve this session knowledge. ASP.NET, how- ever, provides support for maintaining the state of a user’s session. Whenever a page is posted to the server, the server re-creates it from scratch before it is returned to the browser. ASP.NET provides a mechanism that automatically main- tains state for server controls ( ViewState) independent of the HTTP session. Thus, if you provide a list, and the user has made a selection, that selection is preserved after the page is posted back to the server and redrawn on the client. The HTTP session maintains the illusion of a connection between the user and the web application, despite the fact that the Web is a state- less, connectionless environment. Web Forms Life Cycle Every request for a page made to a web server causes a chain of events at the server. These events, from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with a request for the page, which causes the server to load it. When the request is complete, the page is unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to the requesting browser. The life cycle of a page is marked by the following events, each of which you can handle yourself or leave to default handling by the ASP.NET server: Initialize Initialize is the first phase in the life cycle for any page or control. It is here that any settings needed for the duration of the incoming request are initialized. Load ViewState The ViewState property of the control is populated. The ViewState information comes from a hidden variable on the control, used to persist the state across round trips to the server. The input string from this hidden variable is parsed by the page framework, and the ViewState property is set. You can modify this via the LoadViewState( ) method. This allows ASP.NET to manage the state of your control across page loads so that each control isn’t reset to its default state each time the page is posted. Process Postback Data During this phase, the data sent to the server in the posting is processed. If any of this data results in a requirement to update the ViewState, that update is per- formed via the LoadPostData( ) method. Creating a Web Form | 385 Load CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree. State is restored, and the form controls contain client-side data. You can modify the load phase by handling the Load event with the OnLoad( ) method. Send Postback Change Modifications If there are any state changes between the current state and the previous state, change events are raised via the RaisePostDataChangedEvent( ) method. Handle Postback Events The client-side event that caused the postback is handled. PreRender This is your last chance to modify the output prior to rendering, using the OnPreRender( ) method. Save State Near the beginning of the life cycle, the persisted view state was loaded from the hidden variable. Now it is saved back to the hidden variable, persisting as a string object that will complete the round trip to the client. You can override this using the SaveViewState( ) method. Render This is where the output to be sent back to the client browser is generated. You can override it using the Render method. CreateChildControls( ) is called, if necessary, to create and initialize server controls in the control tree. Dispose This is the last phase of the life cycle. It gives you an opportunity to do any final cleanup and release references to any expensive resources, such as database connections. You can modify it using the Dispose( ) method. Creating a Web Form To create the simple Web Form that we will use in the next example, start up Visual Studio .NET and select File ➝ New Web Site. In the New Web Site dialog, choose ASP.NET Web Site from the templates, File System for the location (you can also create web sites remotely using HTTP or FTP), and Visual C# as your language. Give your web site a location and a name and choose your .NET Framework, as shown in Figure 17-1. Visual Studio creates a folder named ProgrammingCSharpWeb in the directory you’ve indicated, and within that directory it creates your Default.aspx page (for the user interface), Default.aspx.cs file (for your code), web.config file (for web site con- figuration settings), and an App_Data directory (currently empty but often used to hold .mdb files or other data-specific files). 386 | Chapter 17: Programming ASP.NET Applications Although Visual Studio no longer uses projects for web applications, it does keep solution files to allow you to quickly return to a web site or desktop application you’ve been developing. The solution files are kept in a directory you can designate through the Tools ➝ Options window, as shown in Figure 17-2. Code-Behind Files Let’s take a closer look at the .aspx and code-behind files that Visual Studio creates. Start by renaming Default.aspx to HelloWeb.aspx. To do this, close Default.aspx and then right-click its name in the Solution Explorer. Choose Rename, and enter the name HelloWeb.aspx. That renames the file, but not the class. To rename the class, right-click the .aspx page, choose View Code in the code page, and then rename the class HelloWeb_aspx. You’ll see a small line next to the name. Click it, and you’ll open the smart tag that allows you to rename the class. Click “Rename ‘_Default’ to ‘HelloWeb_aspx’” and Visual Studio ensures that every occurrence of Default_aspx is replaced with its real name, as shown in Figure 17-3. Within the HTML view of HelloWeb.aspx, you see that a form has been specified in the body of the page using the standard HTML form tag: <form id="form1" runat="server"> Figure 17-1. Creating your new web application Creating a Web Form | 387 Web Forms assume that you need at least one form to manage the user interaction, and it creates one when you open a project. The attribute runat="server" is the key to the server-side magic. Any tag that includes this attribute is considered a server- side control to be executed by the ASP.NET Framework on the server. Within the form, Visual Studio has opened div tags to facilitate placing your controls and text. Having created an empty Web Form, the first thing you might want to do is add some text to the page. By switching to the Source view, you can add script and HTML directly to the file just as you could with classic ASP. Adding to the body seg- ment of the .aspx page the highlighted line in the following code snippet: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="HelloWeb.aspx.cs" Inherits="HelloWeb_aspx" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Figure 17-2. Project location options Figure 17-3. Renaming the class 388 | Chapter 17: Programming ASP.NET Applications <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Hello Web Page</title> </head> <body> <form id="form1" runat="server"> Hello World! It is now <% = DateTime.Now.ToString( ) %> <div> </div> </form> </body> </html> will cause it to display a greeting and the current local time: Hello World! It is now 9/9/2009 5:24:16 PM The <% and %> marks work just as they did in classic ASP, indicating that code falls between them (in this case, C#). The = sign immediately following the opening tag causes ASP.NET to display the value, just like a call to Response.Write( ). You could just as easily write the line as: Hello World! It is now <% Response.Write(DateTime.Now.ToString( )); %> Run the page by pressing F5. Adding Controls You can add server-side controls to a Web Form in three ways: by writing HTML into the HTML page, by dragging controls from the toolbox to the Design page, or by programmatically adding them at runtime. For example, suppose you want to use buttons to let the user choose one of three shippers provided in the Northwind data- base. You can write the following HTML into the <form> element in the HTML window: <asp:RadioButton GroupName="Shipper" id="Speedy" text = "Speedy Express" Checked="True" runat="server"> </asp:RadioButton> <asp:RadioButton GroupName="Shipper" id="United" text = "United Package" runat="server"> Enabling Debugging When you press F5, you begin the debugger. It’s likely that Visual Studio will notice that debugging is not enabled in the Web.config file for this application, and the Debugging Not Enabled dialog box will appear, as shown in Figure 17-4. The default in this dialog box is to modify (and, if needed, create) the Web.config file. Go ahead and click OK to enable debugging for your application. Creating a Web Form | 389 </asp:RadioButton> <asp:RadioButton GroupName="Shipper" id="Federal" text = "Federal Shipping" runat="server"> </asp:RadioButton> The asp tags declare server-side ASP.NET controls that are replaced with normal HTML when the server processes the page. When you run the application, the browser displays three radio buttons in a button group; selecting one deselects the others. You can create the same effect more easily by dragging three buttons from the Visual Studio toolbox onto the form, or to make life even easier, you can drag a radio but- ton list onto the form, which will manage a set of radio buttons declaratively. When you do, the smart tag is opened, and you are prompted to choose a data source (which allows you to bind to a collection; perhaps one you’ve obtained from a data- base) or to edit items. Clicking Edit Items opens the ListItem Collection Editor, where you can add three radio buttons. Each radio button is given the default name ListItem, but you may edit its text and value in the ListItem properties, where you can also decide which of the radio but- tons is selected, as shown in Figure 17-5. You can improve the look of your radio button list by changing properties in the Properties window, including the font, colors, number of columns, repeat direction (vertical is the default), and so forth, as well as by utilizing Visual Studio’s extensive support for CSS styling, as shown in Figure 17-6. In Figure 17-6, you can just see that in the lower-righthand corner you can switch between the Properties window and the Styles window. Here, we’ve used the Proper- ties window to set the tool tip, and the Styles window to create and apply the ListBox style, which creates the border around our listbox and sets the font and font color. We’re also using the split screen option to look at Design and Source at the same time. Figure 17-4. Enabling debugging 390 | Chapter 17: Programming ASP.NET Applications Figure 17-5. List item collection Figure 17-6. Using properties and styles Data Binding | 391 The tag indications (provided automatically at the bottom of the window) show us our location in the document; specifically, inside a ListItem, within the ListBox which is inside a div which itself is inside form1. Very nice. Server Controls Web Forms offer two types of server-side controls. The first is server-side HTML controls. These are HTML controls that you tag with the attribute runat=Server. The alternative to marking HTML controls as server-side controls is to use ASP.NET Server Controls, also called ASP controls or web controls. ASP controls have been designed to augment and replace the standard HTML controls. ASP controls pro- vide a more consistent object model and more consistently named attributes. For example, with HTML controls, there are myriad ways to handle input: <input type="radio"> <input type="checkbox"> <input type="button"> <input type="text"> <textarea> Each behaves differently and takes different attributes. The ASP controls try to nor- malize the set of controls, using attributes consistently throughout the ASP control object model. Here are the ASP controls that correspond to the preceding HTML server-side controls: <asp:RadioButton> <asp:CheckBox> <asp:Button> <asp:TextBox rows="1"> <asp:TextBox rows="5"> The remainder of this chapter focuses on ASP controls. Data Binding Various technologies have offered programmers the opportunity to bind controls to data so that as the data was modified, the controls responded automatically. However, as Rocky used to say to Bullwinkle, “That trick never works.” Bound con- trols often provided the developer with severe limitations in how the control looked and performed. The ASP.NET designers set out to solve these problems and provide a suite of robust data-bound controls, which simplify display and modification of data, sacrificing nei- ther performance nor control over the UI. From version 2.0, they have expanded the list of bindable controls and provided even more out-of-the-box functionality.

Ngày đăng: 07/07/2014, 05:20

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

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

Tài liệu liên quan