Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Pro CSharp 2008 And The .NET 3.5 Platform [eng]

.pdf
Скачиваний:
78
Добавлен:
16.08.2013
Размер:
22.5 Mб
Скачать

1212 CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

Dynamically Adding (and Removing) Controls

Now, what if you wish to modify the contents of a Panel at runtime? Let’s update the current page to support an additional Button (named btnAddWidgets) that dynamically adds three new TextBox types to the Panel, and another Button (named btnRemovePanelItems) that clears the Panel widget of all controls. The Click event handlers for each are shown here:

protected void btnRemovePanelItems_Click(object sender, System.EventArgs e)

{

myPanel.Controls.Clear();

ListControlsInPanel();

}

protected void btnAddWidgets_Click(object sender, System.EventArgs e)

{

for (int i = 0; i < 3; i++)

{

//Assign a name so we can get

//the text value out later

//using the incoming form data.

TextBox t = new TextBox();

t.ID = string.Format("newTextBox{0}", i); myPanel.Controls.Add(t); ListControlsInPanel();

}

}

Notice that you assign a unique ID to each TextBox (e.g., newTextBox1, newTextBox2, and so on) to obtain its contained text programmatically using the HttpRequest.Form collection.

To obtain the values within these dynamically generated TextBoxes, update your UI with one additional Button and Label type. Within the Click event handler for the Button, loop over each item contained within the HttpRequest.NameValueCollection type (accessed via HttpRequest.Form) and concatenate the textual information to a locally scoped System.String. Once you have exhausted the collection, assign this string to the Text property of the new Label widget named lblTextBoxText:

protected void btnGetTextBoxValues_Click(object sender, System.EventArgs e)

{

string textBoxValues = "";

for (int i = 0; i < Request.Form.Count; i++)

{

textBoxValues += string.Format("<li>{0}</li><br/>", Request.Form[i]);

}

lblTextBoxText.Text = textBoxValues;

}

When you run the application, you will find that you are able to view the content of each text box, including some rather long (unreadable) string data. This string contains the view state for each widget on the page and will be examined later in the next chapter. Also, you will notice that once the request has been processed, the text boxes disappear. Again, the reason has to do with the stateless nature of HTTP. If you wish to maintain these dynamically created TextBoxes between postbacks, you need to persist these objects using ASP.NET state programming techniques (also examined in the next chapter).

Source Code The DynamicCtrls project is included under the Chapter 32 subdirectory.

CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

1213

The System.Web.UI.WebControls.WebControl Type

As you can tell, the Control type provides a number of non–GUI-related behaviors (the controls collection, autopostback support, etc.). On the other hand, the WebControl base class provides a graphical polymorphic interface to all web widgets, as suggested in Table 32-2.

Table 32-2. Select Properties of the WebControl Base Class

Property

Meaning in Life

BackColor

Gets or sets the background color of the web control

BorderColor

Gets or sets the border color of the web control

BorderStyle

Gets or sets the border style of the web control

BorderWidth

Gets or sets the border width of the web control

Enabled

Gets or sets a value indicating whether the web control is enabled

CssClass

Allows you to assign a class defined within a Cascading Style Sheet to a web

 

widget

Font

Gets font information for the web control

ForeColor

Gets or sets the foreground color (typically the color of the text) of the web

 

control

Height, Width

Get or set the height and width of the web control

TabIndex

Gets or sets the tab index of the web control

ToolTip

Gets or sets the tool tip for the web control to be displayed when the cursor is

 

over the control

 

 

Almost all of these properties are self-explanatory, so rather than drill through the use of all these properties, let’s shift gears a bit and check out a number of ASP.NET Web Form controls in action.

Major Categories of ASP.NET Web Controls

The types in System.Web.UI.WebControls can be broken down into several major categories:

Simple controls

Feature-rich controls

Data-centric controls

Input validation controls

Web part controls

Security controls

The simple controls are so named because they are ASP.NET web controls that map to standard HTML widgets (buttons, lists, hyperlinks, image holders, tables, etc.). Next, we have a small set of controls named the rich controls for which there is no direct HTML equivalent (such as the Calendar, TreeView, Menu, Wizard, etc.). The data-centric controls are widgets that are typically populated via a given data connection. The best (and most exotic) example of such a control would be the ASP.NET GridView. Other members of this category include “repeater” controls and the lightweight DataList.

1214 CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

The validation controls are server-side widgets that automatically emit client-side JavaScript, for the purpose of form field validation. Finally, the base class libraries ship with a number of security-centric controls. These UI elements encapsulate the details of logging into a site, providing password-retrieval services and managing user roles. The full set of ASP.NET web controls can be seen using the Visual Studio 2008 Toolbox. In Figure 32-2, notice that related controls are grouped together under a specifically named tab.

Figure 32-2. The ASP.NET web controls

A Brief Word Regarding System.Web.UI.HtmlControls

Truth be told, there are two distinct web control toolkits that ship with ASP.NET. In addition to the ASP.NET web controls (within the System.Web.UI.WebControls namespace), the base class libraries also provide the System.Web.UI.HtmlControls widgets.

The HTML controls are a collection of types that allow you to make use of traditional HTML controls on a web forms page. However, unlike raw HTML tags, HTML controls are object-oriented entities that can be configured to run on the server and thus support server-side event handling. Unlike ASP.NET web controls, HTML controls are quite simplistic in nature and offer little functionality beyond standard HTML tags (HtmlButton, HtmlInputControl, HtmlTable, etc.). As you would expect, Visual Studio 2008 provides a specific section of the Toolbox to contain the HTML control types (see Figure 32-3).

The HTML controls provide a public interface that mimics standard HTML attributes. For example, to obtain the information within an input area, you make use of the Value property, rather than the web control–centric Text property. Given that the HTML controls are not as feature-rich as the ASP.NET web controls, I won’t make further mention of them in this text. If you wish to investigate these types, consult the .NET Framework 3.5 SDK documentation for further details.

CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

1215

Figure 32-3. The HTML controls

Note The HTML controls can be useful if your team has a clear division between those who build HTML UIs and

.NET developers. HTML folks can make use of their web editor of choice using familiar markup tags and pass the HTML files to the development team. At this point, developers can configure these HTML controls to run as server controls (by right-clicking an HTML widget within Visual Studio 2008). This will allow developers to handle serverside events and work with the HTML widget programmatically.

Building a Feature-Rich ASP.NET Website

Given that many of the “simple” controls look and feel so close to their Windows Forms counterparts, I won’t bother to enumerate the details of the basic widgets (Buttons, Labels, TextBoxes, etc.). Rather, let’s build a new website that illustrates working with several of the more exotic controls as well as the ASP.NET master page model and enhanced data binding engine. Specifically, this next example will illustrate the following techniques:

Working with master pages

Working with the Menu control

Working with the GridView control

Working with the Wizard control

To begin, create a new ASP.NET Web Application project named AspNetCarsSite.

1216 CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

Working with Master Pages

As I am sure you are aware, many websites provide a consistent look and feel across multiple pages (a common menu navigation system, common header and footer content, company logo, etc.). Under ASP.NET 1.x, developers made extensive use of UserControls and custom web controls to define web content that was to be used across multiple pages. While UserControls and custom web controls are still a very valid option under ASP.NET, we are now provided with the concept of master pages, which complements these existing technologies.

Simply put, a master page is little more than an ASP.NET page that takes a *.master file extension. On their own, master pages are not viewable from a client-side browser (in fact, the ASP.NET runtime will not serve this flavor of web content). Rather, master pages define a common UI frame shared by all pages (or a subset of pages) in your site.

As well, a *.master page will define various content placeholder areas that establish a region of UI real estate other *.aspx files may plug into. As you will see, *.aspx files that plug their content into a master file look and feel a bit different from the *.aspx files we have been examining. Specifically, this flavor of an *.aspx file is termed a content page. Content pages are *.aspx files that do not define an HTML <form> element (that is the job of the master page).

However, as far as the end user is concerned, a request is made to a given *.aspx file. On the web server, the related *.master file and any related *.aspx content pages are blended into a single unified page. To illustrate the use of master pages and content pages, begin by inserting a new master page into your website via the Web Site Add New Item menu selection (Figure 32-4 shows the resulting dialog box).

Figure 32-4. Inserting a new *.master file

CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

1217

The initial markup of the MasterPage.master file looks like the following:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">

<title>Untitled Page</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder>

</head>

<body>

<form id="form1" runat="server"> <div>

<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder>

</div>

</form>

</body>

</html>

The first point of interest is the new <%@Master%> directive. For the most part, this directive supports the same attributes as the <%@Page%> directive described in the previous chapter. Like Page types, a master page derives from a specific base class, which in this case is MasterPage. If you were to open up your related code file, you would find the following class definition:

public partial class MasterPage : System.Web.UI.MasterPage

{

protected void Page_Load(object sender, EventArgs e)

{

}

}

The other point of interest within the markup of the master is the <asp:ContentPlaceHolder> type. This region of a master page represents the area of the master that the UI widgets of the related *.aspx content file may plug into, not the content defined by the master page itself. If you flip to the designer surface of the *.master page, you will find that each <asp:ContentPlaceHolder> element is accounted for, as shown in Figure 32-5.

If you do intend to blend an *.aspx file within this region, the scope within the

<asp:ContentPlaceHolder> and </asp:ContentPlaceHolder> tags will be empty. However, if you so choose, you are able to populate this area with various web controls that function as a default UI to use in the event that a given *.aspx file in the site does not supply specific content. For this example, assume that each *.aspx page in your site will indeed supply custom content, and therefore our

<asp:ContentPlaceHolder> elements will be empty.

Note A *.master page may define as many content placeholders as necessary. As well, a single *.master page may nest additional *.master pages.

1218 CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

Figure 32-5. The design-time view of a *.master file’s <asp:ContentPlaceHolder> tags

As you would hope, you are able to build a common UI of a *.master file using the same Visual Studio 2008 designers used to build *.aspx files. For this site, you will add a descriptive Label (to serve as a common welcome message), an AdRotator control (which will randomly display one of two images), and a Menu control (to allow the user to navigate to other areas of the site). Figure 32-6 shows one possible UI of the master page that we will be constructing (again notice that the content placeholder is empty).

Figure 32-6. The *.master file’s shared UI

CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

1219

Working with the Menu Control and *.sitemap Files

ASP.NET ships with several web controls that allow you to handle site navigation: SiteMapPath, TreeView, and Menu. As you would expect, these web widgets can be configured in multiple ways. For example, each of these controls can dynamically generate its nodes via an external XML file (or an XML-based *.sitemap file), programmatically in code, or through markup using the designers of Visual Studio 2008. Our menu system will be dynamically populated using a *.sitemap file. The benefit of this approach is that we can define the overall structure of our website in an external file, and then bind it to a Menu (or TreeView) widget on the fly. This way, if the navigational structure of our website changes, we simply need to modify the *.sitemap file and reload the page. To begin, insert a new Web.sitemap file into your project using the Web Site Add New Item menu option, to bring up the dialog box shown in Figure 32-7.

Figure 32-7. Inserting a new Web.sitemap file

As you can see, the initial Web.sitemap file defines a topmost item with two subnodes:

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="" title="" description="">

<siteMapNode url="" title="" description="" /> <siteMapNode url="" title="" description="" />

</siteMapNode>

</siteMap>

If we were to bind this structure to a Menu control, we would find a topmost menu item with two submenus. Therefore, when you wish to define subitems, simply define new <siteMapNode> elements within the scope of an existing <siteMapNode>. In any case, the goal is to define the overall structure of your website within a Web.sitemap file using various <siteMapNode> elements. Each one of these elements can define a title and URL attribute. The URL attribute represents which *.aspx file to navigate to when the user clicks a given menu item (or node of a TreeView). Our site contains three subelements, which are set up as follows:

1220 CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

Home: Default.aspx

Build a Car: BuildCar.aspx

View Inventory: Inventory.aspx

Our menu system has a single topmost “Welcome” item with three subelements. Therefore, we can update the Web.sitemap file as follows. (Be aware that each url value must be unique! If not, you receive a runtime error.)

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" > <siteMapNode url="" title="Welcome!" description="">

<siteMapNode url="~/Default.aspx" title="Home" description="The Home Page" />

<siteMapNode url="~/BuildCar.aspx" title="Build a car" description="Create your dream car" />

<siteMapNode url="~/Inventory.aspx" title="View Inventory" description="See what is in stock" />

</siteMapNode>

</siteMap>

Note The ~/ prefix before each page in the url attribute is a notation that represents the root of the website.

Now, despite what you may be thinking, you do not associate a Web.sitemap file directly to a Menu or TreeView control using a given property. Rather, the *.master or *.aspx file that contains the UI widget that will display the Web.sitemap file must contain a SiteMapDataSource component. This type will automatically load the Web.sitemap file into its object model when the page is requested. The Menu and TreeView types then set their DataSourceID property to point to the SiteMapDataSource instance. The reason for this level of indirection is that it makes it possible for us to build a custom provider to fetch the website’s structure from another source (such as a table in a database, an existing XML file, etc.). Figure 32-8 illustrates the interplay between a Web.sitemap, SiteMapDataSource, and various UI elements.

Figure 32-8. The ASP.NET sitemap navigation model

CHAPTER 32 ASP.NET WEB CONTROLS, THEMES, AND MASTER PAGES

1221

To add a new SiteMapDataSource to your *.master file and automatically set the DataSourceID property, you can make use of the Visual Studio 2008 designer. Activate the inline editor of the Menu widget and select New Data Source, as shown in Figure 32-9.

Figure 32-9. Adding a new SiteMapDataSource

From the resulting dialog box, select the SiteMap icon. This will set the DataSourceID property of the Menu item as well as add a new SiteMapDataSource component to your page. This is all you need to do to configure your Menu widget to navigate to the additional pages on your site. If you wish to perform additional processing when the user selects a given menu item, you may do so by handling the MenuItemClick event. There is no need to do so for this example, but be aware that you are able to determine which menu item was selected using the incoming MenuEventArgs parameter.

Establishing Bread Crumbs with the SiteMapPath Type

Before moving on to the AdRotator control, add a SiteMapPath type onto your *.master file, beneath the content placeholder element. This widget will automatically adjust its content based on the current selection of the menu system. As you may know, this can provide a helpful visual cue for the end user (formally, this UI technique is termed bread crumbs). Once you complete this example, you will notice that when you select the Welcome Build a Car menu item, the SiteMapPath widget updates accordingly automatically.

Working with the AdRotator

The role of the ASP.NET AdRotator widget is to randomly display a given image at some position in the browser. When you first place an AdRotator widget on the designer, it is displayed as an empty placeholder. Functionally, this control cannot do its magic until you assign the AdvertisementFile property to point to the source file that describes each image. For this example, the data source will be a simple XML file named Ads.xml.

Once you have inserted this new XML file to your site, specify a unique <Ad> element for each image you wish to display. At minimum, each <Ad> element specifies the image to display (ImageUrl), the URL to navigate to if the image is selected (TargetUrl), mouseover text (AlternateText), and the weight of the ad (Impressions):

<Advertisements>

<Ad>

<ImageUrl>SlugBug.jpg</ImageUrl>

<TargetUrl>http://www.Cars.com</TargetUrl>