Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
1,05 MB
Nội dung
Chapter 3 The Page Rendering Model 61 Of course, using controls on a page usually implies dynamic content, so getting this HTML to the browser should happen dynamically, in a programmatic way. Classic ASP has facilities for rendering dynamic content. However, classic ASP generally relies on raw HTML for ren- dering its content. That means writing a page like the BunchOfControls.htm page shown in Listing 3-1 might look something like Listing 3-2 in classic ASP. Figure 3-2 shows how the ASP page renders in Internet Explorer. LISTING 3-2 Source for BunchOfControls Page Using Classic ASP <%@ Language="javascript" %> <h2> Page in Classic ASP </h2> <form> <label>Type in me</label> <input name="textinfo" type="text" id="textinfo" /> <br/> <select name="selectitems" id="ddl"> <option value="Item 1">Item 1</option> <option value="Item 2">Item 2</option> <option value="Item 3">Item 3</option> <option value="Item 4">Item 4</option> </select> <br/> <input type="submit" name="clickme" value="Click Me!" id="clickme" /> <p> <% if (Request("textinfo") != "") { %> This was in the text box: <%=Request("textinfo") %> <br/> And this was in the selection control: <%=Request("selectitems") %> <% } %> </p> </form> When you select an item from the selection control, notice that the page responds by telling you what you selected. This demonstrates ASP’s support for dynamic content. Notice that even though classic ASP offers a way to decide your page’s content at runtime, you still have to create much of it using raw HTML. Also, the state of the controls is always reset between posts (we’ll look at that when we examine ASP.NET’s ViewState later). ASP.NET adds a layer of indirection between the raw HTML and the rendered page—that layer of indirection is provided by ASP.NET’s collection of server-side controls. Server-side controls eliminate much of the tedium necessary to develop a Web-based UI in classic ASP. <%@ Lan g ua g e=" j avascript" %> < h 2> Page i n C l ass i c ASP < /h 2 > <form > < l a b e l >Type i n me< /l a b e l > <input name="textin f o" type="text" id="textin f o" /> <br /> < se l ect nam e =" se l ect i te m s " i d =" dd l" > <o p tion value="Item 1">Item 1</o p tion > <o p tion value="Item 2">Item 2</o p tion > <o p t i on va l ue= " Item 3 " >Item 3< / o p t i on > <o p t i on va l ue= " Item 4 " >Item 4< / o p t i on > < / se l ect> < b r /> <input type="submit" name="clickme" value="Click Me!" id="clickme" / > <p > <% i f (Re q uest("textin f o") != "") { % > This was in the text box: <%=Re q uest("textin f o") %> <br/ > An d t hi s was i n t h e se l ect i on contro l : <%=Re q uest (" se l ect i tems ") % > <% } % > < /p > < /f orm > 62 Part I Fundamentals Packaging UI as Components Being able to assemble the UI from component parts is one of the most-cited benefi ts of producing components. The earliest technologies for building components in Windows was to write custom Windows Procedures, to use the owner draw capabilities of controls like list boxes or buttons, or to subclass an existing window. In the early 1990s, Windows employed VBXs (Visual Basic Controls) as a viable UI technology. Of course, that was more than a dec- ade ago. Throughout the mid- and late 1990s and early 2000s, ActiveX controls represented the graphical user interface (GUI) componentization technology of the day. Windows Forms controls are the current standard for modular GUIs if you’re writing a rich client application. In the late 1990s, ActiveX controls also emerged as a way to render a Web-based GUI as components. The idea was that by using an ActiveX control in your page, the control would be downloaded as users surfed to the page. During the mid-1990s, Java applets also gained some popularity as a way to package GUI components for distribution over the Web. However, both of these techniques depend on some fairly extensive infrastructure on the client machine (the Component Object Model infrastructure to support ActiveX and a Java Virtual Machine to support Java applets). When you’re developing a Web site, you may not Chapter 3 The Page Rendering Model 63 be able to count on a specifi c infrastructure’s being available on the client machine to sup- port your GUI. To support the greatest number of clients, represent your GUI using only HTML. That means GUI componentization needs to happen on the server side. Now that modern client platforms are becoming more homogeneous, Web UIs are begin- ning to lean increasingly toward the Asynchronous Java And XML programming model (AJAX). We’ll see how AJAX works a bit later. AJAX tends to push more intelligence back up to the browser. However, AJAX applications still have plenty of rendering to do. The ASP.NET UI componentization model makes developing AJAX applications very approach- able. The AJAX programming model includes a lot of underlying plumbing code that fi ts perfectly within the server-side control architecture of ASP.NET. As we saw earlier, ASP.NET introduces an entirely new model for managing Web pages. The infrastructure within ASP.NET includes a well-defi ned pipeline through which a request fl ows. When a request ends up at the server, ASP.NET instantiates a handler (an implementation of IHttpHandler) to deal with the request. As we’ll see in a later chapter, the handling architec- ture is extraordinarily fl exible. You may write any code you wish to handle the request. The System.Web.UI.Page class implements IHttpHandler by introducing an object-oriented ap- proach to rendering. That is, every element you see on a Web page emitted by an ASP.NET page is somehow generated by a server-side control. Let’s see how this works. The Page Using ASP.NET Try turning the previous Web page into an ASP.NET application. Doing so will introduce some canonical features of ASP.NET, including server-side controls and server-side script blocks. 1. Create a fi le named BunchOfControls.aspx. Follow the steps for creating a basic text fi le from the previous chapter. Since all of the code will be in a single fi le, do not create a full-fl edged ASP.NET fi le for this step using the wizard. 2. Add the source code in Listing 3-3 to the fi le. LISTING 3-3 Source Code for BunchOfControls Page Using ASP.NET <%@ Page Language="C#" %> <script runat="server"> protected void Page_Load(object sender, EventArgs ea) { ddl.Items.Add("Item 1"); ddl.Items.Add("Item 2"); ddl.Items.Add("Item 3"); ddl.Items.Add("Item 4"); } </script > <h2> Page in ASP.NET </h2> < %@ Pa g e Lan g ua g e="C#" % > < scri p t runat="server" > protecte d vo id Page_Loa d( o bj ect sen d er, EventArgs ea ) { ddl .Items.A dd(" Item 1 "); ddl .Items.A dd(" Item 2 "); ddl.Items.Add("Item 3") ; ddl.Items.Add("Item 4") ; } < /scri p t > < h2> Pa g e in ASP.NET </h2 > 64 Part I Fundamentals <form id="Form1" runat="server" > <asp:Label Text="Type in me" runat="server" /> <asp:TextBox id="textinfo" runat="server" /> <br/> <asp:DropDownList id="ddl" runat="server" /> <br/> <asp:Button id="clickme" Text="Click Me!" runat="server" /> </form> 3. Save the fi le in a virtual directory (either create one or use the one from the pre vious chapter). Many of the same elements seen in the classic ASP page also appear here. There’s a top-level Page directive. The Language attribute is new for ASP.NET, stipulating that any code encoun- tered by the ASP.NET runtime should be interpreted as C# code. There’s a server-side script block that handles the Page_Load event. Following the script block is an HTML <form> tag. Notice the <form> tag has an attribute named runat, and the attribute is set to server. The runat=server attribute tells the ASP.NET runtime to generate a server-side control to handle that UI element at the server. We’ll see this in detail thoughout the chapter. By including the runat=server attribute in page control tags, the ASP.NET runtime implicitly creates an instance of the control in memory. The resulting assembly includes a member vari- able of the same type and name (tied to the control’s ID value) as the control listed on the page. Notice the ASP.NET code specifi es the DropDownList named ddl to run at the server. To access the control programmatically, the code block (expressed inline in this case) simply needs to refer to the DropDownList as ddl. The example above accesses the member variable to add items to the drop-down list. If you needed to access the control using code beside you’d explicitly declare the DropDownList variable as ddl in the associated code fi le. This is required because ASP.NET derives the code-beside class from System.Web.UI.Page. Visual Studio will do this for you automatically, as we’ll see shortly. Further down the ASP.NET code, you’ll see that the other elements (the label, the text box, the selection control, and the button) are also represented as server-side controls. The job of each of these controls is to add a little bit of HTML to the response. Each time you add a server-side control to the page, ASP.NET adds an instance of the control to a control tree the page maintains in memory. The control tree acts as a container that collects every single ele- ment encapsulated by one of these server-side controls—including the title text that seems to be fl oating near the top of the page even though there is no explicit runat=server attri- bute associated with the <h2> tag. <f orm id="Form1" runat="server" > <asp:Label Text="Type in me" runat="server" /> <asp:TextBox id="textin f o" runat="server" /> <br/ > <as p :Dro p DownList id="ddl" runat="server" / > < b r /> <as p :Button id = " c li c k me " Text= " C li c k Me! " runat= " server " /> </ form> Chapter 3 The Page Rendering Model 65 The Page’s Rendering Model To get a good idea as to how ASP.NET’s Page model works, we’ll run the page again, but this time we’ll turn on the tracing mechanism. We’ll examine tracing in more detail when we look at ASP.NET’s diagnostic features. For now, you simply need to know that ASP.NET will dump the entire context of a request and a response if you set the page’s Trace attribute to true. Here’s the Page directive with tracing turned on: <%@ Page Language="C#" Trace="true" %> Figure 3-3 shows what the page looks like with tracing turned on. FIGURE 3-3 The ASPX fi le from Listing 3-3 rendered in Internet Explorer If you look at the raw text of the response (by selecting View, Source from the Internet Explorer menu), you see that ASP.NET responds with pretty straightforward run-of-the-mill HTML. There’s a bit extra near the top—the hidden __VIEWSTATE fi eld—which we’ll cover later. After that, the rest is familiar HTML describing a form. Listing 3-4 shows the raw HTML emitted by the ASP.NET code from Listing 3-3. Be sure to turn tracing off fi rst! 66 Part I Fundamentals LISTING 3-4 Raw HTML Produced by the BunchOfControls.ASPX File <h2> Page in ASP.NET </h2> <form method="post" action="BunchOfControls.aspx" id="Form1"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJODQ1ODEz " /> </div> <span>Type in me</span> <input name="textinfo" type="text" id="textinfo" /> <br/> <select name="ddl" id="ddl"> <option value="Item 1">Item 1</option> <option value="Item 2">Item 2</option> <option value="Item 3">Item 3</option> <option value="Item 4">Item 4</option> </select> <br/> <input type="submit" name="clickme" value="Click Me!" id="clickme" /> </form> You don’t see any of the runat=server attributes anywhere in the rendered page. That’s be- cause the runat=server attributes are there to instruct ASP.NET how to construct the page’s control tree. The Page’s Control Tree After turning the page’s Trace property to true, ASP.NET will spew a ton of information your way in the form of a page trace. If you scroll down just a bit, you can see that part of ASP .NET’s page trace includes the page’s control tree. Figure 3-4 shows what the previous page’s trace looks like with the focus on the control tree. The fi rst line in the page’s control tree trace is an item named __Page. This is in fact the System .Web.UI.Page object running in memory. Beneath that are a whole host of other items. You’ll recognize some of their names as they were named in the ASP.NET source code. Notice the Form1, textinfo, and clickme items. Those names came from the tags in the original ASPX fi le. What’s happening here is that ASP.NET is breaking down the page rendering architecture into small, easily managed pieces. Every item in the control tree shown in Figure 3-4 derives from the System.Web.UI.Control class. Every time the System.Web.UI.Page needs to render the page, it simply walks the control tree, asking each control to render itself. For example, when the ASP.NET runtime asks the TextBox server-side control to render itself, the TextBox control adds the following HTML to the output stream heading for the browser: <input name="textinfo" type="text" id="textinfo" /> Chapter 3 The Page Rendering Model 67 This works similarly for the other controls. For example, the DropDownList is responsible for emitting the select and option tags (the option tags represent the collection of items held by the DropDownList control). <select name="ddl" id="ddl"> <option value="Item 1">Item 1</option> <option value="Item 2">Item 2</option> <option value="Item 3">Item 3</option> <option value="Item 4">Item 4</option> </select> Now that you see how these tags work, let’s see how to manage them in Visual Studio. 68 Part I Fundamentals Adding Controls Using Visual Studio Visual Studio (in concert with ASP.NET) is very good at fooling you as to the real nature of Web-based development. As you saw from earlier chapters, Web-based development hearkens back to the old terminal–mainframe days of the mid-1970s. However, this time the terminal is a sophisticated browser, the computing platform is a Web server (or perhaps a Web farm), and the audience is worldwide. When a client browser makes a round-trip to the server, it’s really getting only a snapshot of the state of the server. That’s because Web user interfaces are built using a markup language over a disconnected protocol. When you build Web applications in Visual Studio, it’s almost as if you’re developing a desk- top application. With Visual Studio, you don’t have to spend all your time typing ASP-style code. The designer is a great environment for designing a Web-based UI visually. Building a Page with Visual Studio To see how this works, let’s develop a simple page that uses server-side controls. The page will look roughly like the ones we’ve seen so far. 1. Create a Web site to experiment with controls. Use Visual Studio to create a new fi le system–based ASP.NET Web site. Call the Web site ControlORama, as shown here: 2. Use the Designer. Visual Studio starts you off editing the markup in the Default.aspx fi le. If you don’t see the page layout designer mode, switch to the Design view as shown here by clicking on the Design tab near the bottom of the edit window. Chapter 3 The Page Rendering Model 69 The ASP.NET code generated by Visual Studio includes an HTML <div> tag in the body of the page. To see the code generated by Visual Studio as you modify elements in the designer, select the Source tab near the bottom of the design window. Visual Studio now includes a handy Split tab that allows you to see both the design and source views at the same time. If you simply start typing some text into the Design view, you’ll see some text at the top of the page. The following graphic illustrates the Design view with some text in serted. To insert the text, click inside the box with the dashed blue border and type Page in Visual Studio: 70 Part I Fundamentals 3. Format the text on the page. To edit the format of the text on the page, you need to view the page’s properties. Highlight the text, click the right mouse button the text, and select Properties from the local menu. Then highlight the Style property in the Property dialog box. You’ll see a small button appear in the Property fi eld with an ellipsis (. . .). Click the button to reveal the Modify Style dialog box. The Modify Style dialog box sets the attributes for the <div> tag where you can set the font face and style. The fol- lowing graphic shows the Modify Style dialog box. Make the selections for font-family, font-size, and font-weight you see in the graphic and click OK: 4. Open the Control toolbox. Next add a label to the page. Move the cursor to the Toolbox tab on the far left side of Visual Studio. This will highlight the toolbox on the left as shown in the following graphic: [...]... Item 1< /asp: ListItem> Item 2< /asp: ListItem> Item 3< /asp: ListItem> Item 4< /asp: ListItem> < /asp: DropDownList> Notice each ASP. NET tag that runs at the server is given an ID attribute This is the identifier by which the control will be known at runtime We’ll... Final Default.aspx Markup Page in Visual Studio < /asp: Label> < /asp: TextBox> Item 1< /asp: ListItem> Item... was somehow generated by a server-side control Even literal text on the page was rendered using a LiteralControl When the ASP. NET runtime compiles a page, it scans the ASPX file for any tag that says runat=server and adds a member variable representing that control to the page’s control tree Nothing escapes being packaged as a control—when ASP. NET finds literal text on the page, ASP. NET packages that as... they detect the differences in client browsers Let’s start by looking at the heart of the ASP. NET server-side control architecture—the System.Web.UI.Control class The Control Class ASP. NET server-side controls derive from a class named System.Web.UI.Control In fact, the Control class is the core of almost every User Interface element within ASP. NET Even System Web.UI.Page is derived from the Control class... events within the control Use ASP. NET to detect differences in client browsers and apply that information In Chapter 3, “The Page Rendering Model,” we saw the fundamental architecture behind the ASP. NET rendering model System.Web.UI.Page manages a list of server-side controls, and it’s the job of each server-side control to render a particular portion of the page ASP. NET broadly classifies server-side... UseCustomControl.aspx Markup < /asp: Label> < /asp: TextBox> Chapter 4 Custom Rendered Controls 87 Notice that the standard ASP. NET controls (the button, the text box, and the label) all begin with the asp: prefix while the new custom control uses the prefix cc1: Visual Studio made up the tag cc1:, although you could change this for this page by modifying the TagPrefix attribute in the Register directive 7 Add an event handler for the button by double-clicking the button in the designer... System.Web.UI.Page class The entries in Table 4-1 show a small cross section of the functionality available within System.Web.UI.Control We’ll visit all these members while investigating ASP. NET Web forms Remember from the last chapter that ASP. NET Web forms manage a collection of controls as part of their internal structure As you add controls to a Web page, they’re placed within the collection When it comes time... property is showing after you change it in the designer The following line of code is what Visual Studio added to the ASPX file to accommodate the control You can see it by selecting the Source tab from the bottom of the code window in Visual Studio The Register directive tells the ASP. NET runtime where to find the custom control (which assembly) and maps it to a tag prefix . Figure 3- 3 shows what the page looks like with tracing turned on. FIGURE 3- 3 The ASPX fi le from Listing 3- 3 rendered in Internet Explorer If you look at the raw text of the response (by selecting. Listing 3- 4 shows the raw HTML emitted by the ASP. NET code from Listing 3- 3. Be sure to turn tracing off fi rst! 66 Part I Fundamentals LISTING 3- 4 Raw HTML Produced by the BunchOfControls.ASPX. Listing 3- 1 might look something like Listing 3- 2 in classic ASP. Figure 3- 2 shows how the ASP page renders in Internet Explorer. LISTING 3- 2 Source for BunchOfControls Page Using Classic ASP <%@