Chapter 3 The Page Rendering Model 61Of course, using controls on a page usually implies dynamic content, so getting this HTML to the browser should happen dynamically, in a programmati
Trang 1Chapter 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
<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>
This was in the text box: <%=Request("textinfo") %> <br/>
And this was in the selection control: <%=Request("selectitems") %>
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
<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>
This was in the text box: <%=Request("textinfo") %> <br/>
And this was in the selection control: <%=Request("selectitems") %>
<% } %>
</p>
</form>
Trang 2In 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
Trang 3Chapter 3 The Page Rendering Model 63
be able to count on a specifi c infrastructure’s being available on the client machine to 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
sup-Now that modern client platforms are becoming more homogeneous, Web UIs are 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
begin-to the browser However, AJAX applications still have plenty of rendering begin-to do The
ASP.NET UI componentization model makes developing AJAX applications very 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
approach-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
Trang 4<form id="Form1" runat="server" >
<asp:Label Text="Type in me" runat="server" />
<asp:TextBox id="textinfo" runat="server" />
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 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
vari-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
<form id="Form1" runat="server" >
<asp:Label Text="Type in me" runat="server" />
<asp:TextBox id="textinfo" runat="server" />
Trang 5Chapter 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!
Trang 6LISTING 3-4 Raw HTML Produced by the BunchOfControls.ASPX File
<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" />
Trang 7Chapter 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
Trang 8Adding 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 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
Trang 9Chapter 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:
Trang 103 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:
Trang 11Chapter 3 The Page Rendering Model 71
5 Add a label to the page Drag a label from the Toolbar and drop it onto the page, then
select it as shown in the following graphic (notice how Visual Studio 2008’s designer adorns the label with a small tag right above it, helping you identify the label in the de-signer when you select it):
6 Edit the content of the label To edit the content of the label, you need to view the
con-trol’s properties If the properties aren’t showing, click the right mouse button on the label and select Properties from the shortcut menu The following graphic illustrates
the property window:
Trang 12You can now manipulate the appearance of the label to your liking The example label here uses a small Times New Roman font and the text in the label is Type in me:
7 Add a text box. Next, pick up a TextBox from the toolbox and drop it next to the Label
(you can pick up a TextBox from the toolbox—just as you did with the Label) Follow the TextBox with a line break tag (<br/>)
8 Add a drop-down list. Next, add a DropDownList box by picking it up off the Toolbox
and dropping it onto the page The following graphic illustrates the drop-down list as
it appears in the designer Notice the local menu for editing the data source and for adding/editing items
As soon as you drop the control onto the page, Visual Studio prompts you with the opportunity to add items to the DropDownList Select Edit Items from the Common
DropDownList Tasks window You’ll see the ListView Collection Editor dialog box as
shown in the following graphic:
Trang 13Chapter 3 The Page Rendering Model 73
Each time you click the Add button, the ListView Collection Editor adds a new item to
the DropDownList item collection You can edit the display name (the Text property)
You may add a corresponding value to associate with the text as well For example, in
an inventory-tracking application, you might include a product name as the Text
prop-erty and an enterprise-specifi c product code in the Value fi eld You can retrieve either
or both aspects of the item at runtime
Add several of these items to the DropDownList as shown in the following graphic
When you’ve added several, click OK:
9 Add a button to the page First, add a line break following the DropDownList Then pick
up a Button from the Toolbox and drop it on the page The following graphic shows the
controls in place:
Trang 14Add some meaningful text to the button by modifying its Text property
Before moving on, take a minute to look at the source code generated by Visual Studio
In adding a Label control, a TextBox control, a DropDownList control, and a Button
con-trol, Visual Studio has added four new member variables to your code (implied through the runat=server attributes placed within the control tags) The contents of the ASPX
fi le (starting with the form tag) look something like Listing 3-5 at this point
LISTING 3-5 Final Default.aspx Markup
<form id="form1" runat="server">
<div style="font-weight: bold; font-size: 14pt; font-family: 'Times New Roman'"> Page in Visual Studio<br />
<asp:Label ID="Label1" runat="server"
Notice each ASP.NET tag that runs at the server is given an ID attribute This is the
iden-tifi er by which the control will be known at runtime We’ll make use of that shortly
10 Add an event handler for the button Finally, to make the button do something, you
need to add an event handler to the page so it will respond when the button is clicked The easiest way to do that is to double-click on the button in Design mode Visual Studio will generate a handler function for the button click and then show that code in the Source code view At this point, you can add some code to respond to the button click
Add the source code in Listing 3-6 to the fi le
LISTING 3-6 Button Handling Code
protected void Button1_Click(object sender, EventArgs e)
Trang 15Chapter 3 The Page Rendering Model 75
The code shown above responds to the button click by sending some text to the put stream via the Response object The text coming through Response.Write will be the
out-fi rst text the client browser will see, and so will appear at the top of the page
Notice that the response code uses the TextBox1 member variable in the page’s class,
showing that the controls are available programmatically at runtime Here’s how the page appears to the client browser Notice how the text emitted by Response.Write is
inserted before any of the controls are:
To test the controls on the page, browse to the page by selecting Debug, Start Without Debugging from the main menu To see the HTML generated by all the server-side controls,
you may view the source sent to the browser (if your browser is Microsoft Internet Explorer, choose View, Source from the menu) When you view the source, you should see something
like that shown in Listing 3-7 Notice how the text emitted by Response.Write appears at the
very top of the listing
LISTING 3-7 HTML Resulting from Running Default.aspx
Hello Here's what you typed into the text box: <br>
Hello World<br>
And the selected item is: <br>Item 1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"