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

Pro CSharp And The .NET 2.0 Platform (2005) [eng]

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

874CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

Home: Default.aspx

Build a Car: BuildCar.aspx

View Inventory: Inventory.aspx

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.

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> <AlternateText>Your new Car?</AlternateText> <Impressions>80</Impressions>

</Ad>

<Ad>

<ImageUrl>car.gif</ImageUrl>

<TargetUrl>http://www.CarSuperSite.com</TargetUrl> <AlternateText>Like this Car?</AlternateText> <Impressions>80</Impressions>

</Ad>

</Advertisements>

At this point, you can associate your XML file to the AdRotator controls via the AdvertisementFile property (in the Properties window):

<asp:AdRotator ID="myAdRotator" runat="server" AdvertisementFile="~/Ads.xml"/>

Later when you run this application and post back to the page, you will be randomly presented with one of two image files. Figure 23-21 illustrates the initial UI of the master page.

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

875

Figure 23-21. The master page

Defining the Default.aspx Content Page

Now that you have a master page established, you can begin designing the individual *.aspx pages that will define the UI content to merge within the <asp:contentplaceholder> tag of the master page. When you created this new website, Visual Studio 2005 automatically provided you with an initial *.aspx file, but as the file now stands, it cannot be merged within the master page.

The reason is that it is the *.master file that defines the <form> section of the final HTML page. Therefore, the existing <form> area within the *.aspx file will need to be replaced with an <asp:content> scope. Flip to the Source view of Default.aspx and replace the existing markup with the following:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"

AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Title="Untitled Page" %>

<asp:Content ID="Content1"

ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> </asp:Content>

First, notice that the <%@Page%> directive has been updated with a new MasterPageFile attribute that is assigned to your *.master file. Also note that the ContentPlaceHolderID value is identical to the <asp:contentplaceholder> widget in the master file.

Given these associations, you will now find that when you switch back to the Design view, the master’s UI is now visible. The content area is visible as well, although it is currently empty. There is no need to build a complex UI for your Default.aspx content area, so for this example, simply add a few Labels to hold some basic site instructions (see Figure 23-22).

876 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

Figure 23-22. The Default.aspx content page

Now, if you run your project, you will find that the UI content of the *.master and Default.aspx files have been merged into a single stream of HTML. As you can see from Figure 23-23, the end user is unaware that the master page even exists.

Figure 23-23. The default page of Cars R Us

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

877

Designing the Inventory Content Page

To insert the Inventory.aspx content page into your current project, open the *.master page in the IDE and select WebSite Add Content Page (if a *.master file is not the active item in the designer, this menu option is not present). The role of the Inventory content page is to display the contents of the Inventory table of the Cars database within a GridView control.

As you may know, the GridView control is not limited to read-only data display. This widget can be configured to support sorting, paging, and in-place editing. If you wish, you can handle a series of server-side events and author ADO.NET code to do so; this ASP.NET 2.0 widget supersedes the ASP.NET 1.x control with a “zero-code” mentality.

With a few simple mouse clicks you can configure the GridView to automatically select, update, and delete records of the underlying data store. While this zero-code mind-set greatly simplifies the amount of boilerplate code, understand that this simplicity comes with a loss of control and may not be the best approach for an enterprise-level application.

Nevertheless, to illustrate how to work with the GridView in this declarative manner, insert a new content page (Inventory.aspx) and update the content area with a descriptive label and a GridView. Using the inline editor, select New Data Source from the Choose Data Source drop-down box. This will activate a wizard that walks you through a series of steps to connect this component to the required data source. Here are the steps to take for the current example:

1.Select the Database icon and change the name of the data source ID to CarsDataSource.

2.Select the Cars database (create a new connection if required).

3.If you wish, save the connection string data to a Web.config file. Recall from Chapter 22 that ADO.NET now supports the <connectionStrings> element.

4.Configure your SQL Select statement to select all records from the Inventory table (Figure 23-24 shows the settings I chose).

5.Test your query and click the Finish button.

Figure 23-24. Selecting the Inventory table

878 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

Now, if you examine the opening declaration of the GridView control, you will see that the DataSourceID property has been set to the SqlDataSource you just defined:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="CarID" DataSourceID="CarsDataSource" ForeColor="#333333" GridLines="None">

...

</asp:GridView>

The SqlDataSource type (new to .NET 2.0) is a component that encapsulates the details of

a given data store. Given your work in Chapter 23, the following attributes should be straightforward:

<asp:SqlDataSource ID="CarsDataSource" runat="server" ConnectionString=

"Data Source=localhost;Initial Catalog=Cars;Integrated Security=True" ProviderName="System.Data.SqlClient"

SelectCommand="SELECT * FROM [Inventory]"> </asp:SqlDataSource>

At this point, you are able to run your web program, click the View Inventory menu item, and view your data (see Figure 23-25).

Figure 23-25. The no-code GridView

Enabling Sorting and Paging

The GridView control can easily be configured for sorting (via column name hyperlinks) and paging (via numeric or next/previous hyperlinks). To do so, activate the inline editor and check the appropriate options (see Figure 23-26).

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

879

Figure 23-26. Enabling paging and sorting

When you run your page again, you will be able to sort your data by clicking the column names and scrolling through your data via the paging links (provided you have enough records in the Inventory table!).

Enabling In-Place Editing

The final detail of this page is to enable the GridView control’s support for in-place activation. To do so, open the inline editor for the SqlDataSource and select Configure Data Source. Skip past the first two steps of this wizard, but on Step 3, click the Advanced button and check the first option (see Figure 23-27).

Figure 23-27. Generating the remaining SQL statements

If you examine the HTML definition of the control, you will now find the following that the

SqlDataSource has been equipped with a DeleteCommand, InsertCommand, and UpdateCommand (each of which is making use of parameterized queries):

<asp:SqlDataSource ID="CarsDataSource" runat="server" ConnectionString=

"Data Source=localhost;Initial Catalog=Cars;Integrated Security=True"

880 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

ProviderName="System.Data.SqlClient" SelectCommand="SELECT * FROM [Inventory]"

DeleteCommand="DELETE FROM [Inventory] WHERE [CarID] = @original_CarID" InsertCommand="INSERT INTO [Inventory] ([CarID], [Make], [Color], [PetName]) VALUES (@CarID, @Make, @Color, @PetName)"

UpdateCommand="UPDATE [Inventory] SET

[Make] = @Make, [Color] = @Color, [PetName] = @PetName WHERE [CarID] = @original_CarID">

...

</asp:SqlDataSource>

As well, you are provided with a SqlDataSource component giving additional markup that defines the parameter objects for the parameterized queries:

<DeleteParameters>

<asp:Parameter Name="original_CarID" Type="Int32" /> </DeleteParameters>

<UpdateParameters>

<asp:Parameter Name="Make" Type="String" /> <asp:Parameter Name="Color" Type="String" /> <asp:Parameter Name="PetName" Type="String" /> <asp:Parameter Name="original_CarID" Type="Int32" />

</UpdateParameters>

<InsertParameters>

<asp:Parameter Name="CarID" Type="Int32" /> <asp:Parameter Name="Make" Type="String" /> <asp:Parameter Name="Color" Type="String" /> <asp:Parameter Name="PetName" Type="String" />

</InsertParameters>

The final step is to enable editing and deleting support via the inline editor of the GridView (see Figure 23-28).

Figure 23-28. Enabling editing and deleting support

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

881

Sure enough, when you navigate back to the Inventory.aspx page, you are able to edit and delete records (see Figure 23-29).

Figure 23-29. The grids of all grids

Designing the Build a Car Content Page

The final task for this example is to design the BuildCar.aspx content page. Insert this current project (via the WebSite Add Content Page menu option). This new page will make use of the ASP.NET 2.0 Wizard web control, which provides a simple way to walk the end user through a series of related steps. Here, the steps in question will simulate the act of building an automobile for purchase. Place a descriptive Label and Wizard control onto the content area. Next, activate the inline

editor for the Wizard and click the Add/Remove WizardSteps link. Add a total of four steps, as shown in Figure 23-30.

882 CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

Figure 23-30. Configuring Wizard steps

Once you have defined these steps, you will notice that the Wizard defines an empty content area where you can now drag and drop controls for the currently selected step. For this example, update each step with the following UI elements (be sure to provide a descent ID value for each item using the Properties window):

Pick Your Model: A single TextBox control

Pick Your Color: A single ListBox control

Name Your Car: A single TextBox control

Delivery Date: A Calendar control

The ListBox control is the only UI element of the Wizard that requires additional steps. Select this item on the designer (making sure your first select the Pick Your Color link) and fill this widget with a set of colors using the Items property of the Properties window. Once you do, you will find markup much like the following within the scope of the Wizard definition:

<asp:ListBox ID="ListBoxColors" runat="server" Width="237px"> <asp:ListItem>Purple</asp:ListItem> <asp:ListItem>Green</asp:ListItem> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Yellow</asp:ListItem>

<asp:ListItem>Pea Soup Green</asp:ListItem> <asp:ListItem>Black</asp:ListItem> <asp:ListItem>Lime Green</asp:ListItem>

</asp:ListBox>

Now that you have defined each of the steps, you can handle the FinishButtonClick event for the autogenerated Finish button. Within the server-side event handler, obtain the selections from each UI element and build a description string that is assigned to the Text property of an additional

Label type named lblOrder:

protected void carWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)

{

// Get each value.

string order = string.Format("{0}, your {1} {2} will arrive on {3}.",

CHAPTER 23 ASP. NET 2 . 0 WEB PAGES AND WEB CONTROLS

883

txtCarPetName.Text, ListBoxColors.SelectedValue, txtCarModel.Text, carCalendar.SelectedDate.ToShortDateString());

// Assign to label lblOrder.Text = order;

}

At this point your AspNetCarSite is complete. Figure 23-31 shows the Wizard in action.

Figure 23-31. The Wizard in action

That wraps up our examination of various UI web controls. To be sure, there are many other widgets we haven’t covered here. You should feel comfortable, though, with the basic programming model. To wrap things up for this chapter, let’s look at the validation controls.

Source Code The AspNetCarsSite files are included under the Chapter 23 subdirectory.

The Role of the Validation Controls

The final group of Web Form controls we will examine is termed validation controls. Unlike the other Web Form controls we’ve examined, validator controls are not used to emit HTML, but are used to emit client-side JavaScript (and possibly server-side operations) for the purpose of form validation. As illustrated at the beginning of this chapter, client-side form validation is quite useful in that you can ensure that various constraints are in place before posting back to the web server, thereby avoiding expensive round-trips. Table 23-11 gives a rundown of the ASP.NET validation controls.