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

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

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

Chapter 13

Figure 13-9

11.Click OK. Select the smart tag dialog box that appears next to PriceLabel and select Edit DataBindings (see Figure 13-10). This time select the Text property under Bindable properties, and select the Currency option from the Format drop-down list.

Figure 13-10

12.Click OK. You have a couple of final tasks to perform. Go to the smart tag dialog and select End Template Editing. Click the smart tag dialog box by the DataList control and select Property builder. Set the Columns to 4 and change the Direction from Vertical to Horizontal, as shown in Figure 13-11. Then click OK.

13.You’ve now finished the layout of the catalog. Run the project and view the catalog. It should look like Figure 13-12.

468

E-Commerce

Figure 13-11

Figure 13-12

469

Chapter 13

How It Works

You created a catalog that pretty much resembles the one on the Wrox United web site. You created your images as image buttons, which will eventually act as links to the individual product item page. If you click an image, it doesn’t take you anywhere (yet), but in all other respects it is the same as the example site. In this Try It Out, two controls do the work. If you go back to Visual Web Developer and view the source for this page, you will see the following code:

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited %>” SelectCommand=”SELECT [Name], [Description], [Price], [ProductID], [PictureURL] FROM [Products]”>

</asp:SqlDataSource>

<asp:DataList ID=”DataList1” runat=”server” DataKeyField=”ProductID” DataSourceID=”SqlDataSource1” RepeatColumns=”4” RepeatDirection=”Horizontal”>

<ItemTemplate>

<asp:ImageButton ID=”ImageButton1” runat=”server” ImageUrl=’<%# Eval(“PictureURL”, “ProductImages\\thumb_{0}”) %>’ /><br /> <asp:Label ID=”NameLabel” runat=”server” Text=’<%# Eval(“Name”)%>’> </asp:Label><br />

<asp:Label ID=”PriceLabel” runat=”server” Text=’<%# Eval(“Price”, “{0:C}”) %>’></asp:Label>

</ItemTemplate>

</asp:DataList>

The first control, SqlDataSource1, is the one that sources your catalog. The details of what is for sale in the Wrox United web site are stored in the Products table. It contains the connection string that enables you to connect to the database, as well as a SelectCommand attribute that specifies the SQL that will pluck the Name, Description, Price, ProductID, and the URL of the image from the Products table. The SqlDataSource on its own doesn’t display anything, though. It needs the DataList to do this for it.

The DataList contains three controls as well as the formatting needed to display your catalog correctly. You started by replacing the Label control contained for PictureURL with an Image button. You did this because, if you hadn’t, a label would just have displayed the text URL of the image, such as ProductImages\Item1.gif. Secondly, you chose an ImageButton in place of an image because you needed a link to the product item page. Rather than having to move or re-create this folder of product images, we placed it in the web site folder already, and all you had to do is reference it as follows:

Eval(“PictureURL”, “ProductImages\\thumb_{0}”)

The data-binding expression has two parameters: the first is the name of the field from the Products table you want to bind to your image button and the second is the contents of the field itself (indicated by {0}). You altered the second parameter so that it pointed to the ProductImages folder. Then you placed “thumb_”, which indicates that you don’t want to use a full-sized image, but instead, you want to usea thumbnail of the image for the catalog.

You used labels for the other two items in the catalog, because you only needed to display text, but for your price, you changed the format so that it displayed it in currency format as $0.00, rather than just 0.0000. Last, you altered the layout so that it displayed the items in a horizontal grid format, four across in each row.

470

E-Commerce

The Product Item Page

In our design discussion, we talked about all the possible features you might want to add to a specific product page, but settled on only really needing an enhanced description of the product. Of course your item page shouldn’t contain any less information about the product than the catalog, so you will need to display the name, image, and price in addition to the description. You add that to your web site in the following Try It Out.

Try It Out

Building a Product Page for the Catalog

1.Go to Solution Explorer, right-click the top item in it, and select Add New Item. Add a new Web Form and call it WroxShopItem.aspx.

2.Once again you need the SqlDataSource and DataList controls. In Design View, drag a SqlDataSource control from the Data section of the Toolbox.

3.Click the Configure Data Source flyout of the SqlDataSource control and select the WroxUnitedUnitedConnectionString from the drop-down list in the Choose your Data Connection dialog box that appears.

4.Click Next and, as with the previous Try It Out, select the Products table and select each of the items within it, as shown in Figure 13-13.

Figure 13-13

471

Chapter 13

5.Click WHERE. You will be presented with the screen depicted in Figure 13-14. Select ProductID from the Column drop-down list; select QueryString from the Source drop-down list; and type in ProductID to the QueryString field, leaving the Default value blank. This step allows you to hone in on your single selected product. You use the filter clause to match the product ID of the selected product and therefore only show details about that particular product. Click Add.

Figure 13-14

6.Click OK, and then click Next and Finish to return to Design View.

7.Add a DataList control, click Configure DataSource, and select SqlDataSource1 from the Choose Data Source drop-down list.

8.Click Edit Templates from the list, and delete all the text alongside the labels. Move the PictureURL label to the top. This time, only remove the product ID label, so that it now looks like Figure 13-15.

Figure 13-15

9.Right-click PictureURLLabel and select Properties. In the Properties window, change the Visible property to false. You’re going to need the URL, but you don’t want it displayed on the

472

E-Commerce

screen. PictureURLLabel is used to provide the URL of where to find the image of your product; however, you don’t want the actual URL text displayed, but rather the image itself.

10.In Design View, add an Image control from the Standard section of the Toolbox to the top of the controls.

11.Click the smart tag dialog box next to the Image control and select Edit Data Bindings.

12.In the dialog box that appears, click Custom Bindings and amend the text so that it reads as follows (which is slightly differently from the last Try It Out, because you want a full-sized version of the image, not a thumbnail):

Eval(“PictureURL”, “ProductImages\\{0}”)

13.Click OK, and then go to Price Label and select the Edit Data Bindings option from the menu that appears when you click the black arrow. Enter the following code in the Custom Bindings drop-down list box:

Eval(“Price”, “{0:##0.00}”)

This is slightly different from before, because you want to use the currency format. However, currency format adds a $ symbol, and you want to use this value in your code later, so you don’t want to include the $ symbol in the label.

14.Click OK. In Design View, select Hyperlink from the Standard section of the Toolbox menu and place it below the DataList control, as shown in Figure 13-16.

Figure 13-16

15.Right-click HyperLink and select the Properties option. Change the Text property so it reads Return to Shop, and change the NavigateURL property so that it reads ~/WroxShop.aspx, as shown in Figure 13-17. Alternatively, you can click the ellipsis button in the NavigateURL property box and choose wroxshop from there.

16.Close the Properties window, and go to Design View in the first page you created (WroxShop

.aspx).

473

Chapter 13

Figure 13-17

17.Select the DataList control underneath SqlDataSource1. From the smart tag dialog box, select Edit Templates Item Template.

18.Go to the Image Button (the graphic with the red cross), click the smart tag dialog box, and select Edit Data Bindings.

19.Click Show All Properties and select PostbackURL. Check the Custom bindings and change it so that it reads as follows:

Eval(“ProductID”,”WroxShopItem.aspx?ProductID={0}”)

20.Click End Template Editing for both pages, run the application from WroxShop.aspx, and click the Scarf image. You should see what appears in Figure 13-18.

21.To get details about another product, click Return to Shop and go back and select the corresponding product image.

474

E-Commerce

Figure 13-18

How It Works

The Product Item page is put together in much the same way as the Product Catalog, the main difference being that instead of all of the items being viewed, you only want to look at the details of a single item. If you view the source, you will see that it comprises the SqlDataSource and DataList controls:

<form id=”form1” runat=”server”>

<asp:SqlDataSource ID=”SqlDataSource1” runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited %>”

SelectCommand=”SELECT DISTINCT [ProductID], [Name], [Description], [Price], [PictureURL] FROM [Products] WHERE ([ProductID] = @ProductID)”>

<SelectParameters>

<asp:QueryStringParameter Name=”ProductID” QueryStringField=”ProductID” Type=”Int32” />

</SelectParameters>

</asp:SqlDataSource>

<asp:DataList ID=”DataList1” runat=”server” DataKeyField=”ProductID” DataSourceID=”SqlDataSource1”>

<ItemTemplate>

<asp:Label visible=”false” ID=”PictureURL” Text=’<%#Eval(“PictureURL”)%>’ />

<asp:Image ID=”Image1” runat=”server” ImageUrl=’<%# Eval(“PictureURL”, “ProductImages\\{0}”) %>’ /><br /> <asp:Label ID=”NameLabel” runat=”server” Text=’<%# Eval(“Name”) %>’></asp:Label><br />

<asp:Label ID=”DescriptionLabel” runat=”server” Text=’<%#

475

Chapter 13

Eval(“Description”) %>’> </asp:Label><br />

<asp:Label ID=”PriceLabel” runat=”server” Text=’<%# Eval(“Price”, “{0:##0.00}”) %>’></asp:Label><br />

<br /> <br />

</ItemTemplate>

</asp:DataList>

<asp:HyperLink ID=”HyperLink1” runat=”server” NavigateUrl=”~/WroxShop.aspx”>Return to Shop</asp:HyperLink>

</form>

The difference is that this time the SqlDataSource’s SelectCommand attribute has an extra WHERE clause:

SelectCommand=”SELECT DISTINCT [ProductID], [Name], [Description], [Price], [PictureURL] FROM [Products] WHERE ([ProductID] = @ProductID)”

This references a ProductID parameter. Underneath this element, the SqlDataSource1 also contains a SelectParameters element, which specifies where you are going to get the parameter from:

<SelectParameters>

<asp:QueryStringParameter Name=”ProductID” QueryStringField=”ProductID” Type=”Int32” />

</SelectParameters>

These parameters are used to transfer the details about the item you have clicked. This is where the hidden ProductID comes into play. You haven’t used it so far, but now you most definitely need it. Each item in your catalog has a unique identifier, this being ProductID. You collect ProductID when the image is collected and send it as a QueryString as follows:

http://localhost/Chapter13/WroxShopItem.aspx?ProductID=1

Then your second page (WroxShopItem.aspx) is able to pick that up and use it in the WHERE clause of the SELECT command of the SqlDataSource control to return the details of that single item. The DataList control of WroxShopItem is similar to the WroxShop DataList control. The are only two changes, the first being that instead of referencing the thumbnail version of the image, you just use the whole version of the image. Space is no longer such an essential here, because you don’t have to worry about nine other items. The second change is that you have added the Description from the Products table as an extra label. You’ve also used the PictureURL from PictureURLLabel as a URL for your <asp:Image> control that you use to display the merchandise. Apart from that, it is business as usual.

You’re actually quite a distance into this chapter and so far you haven’t created anything totally specific to e-commerce. The problem is that without a catalog and a set of items, you have nothing to put into your cart. The order in which you create things is essential. Now that you have a catalog and the ability to browse specific items in the catalog, it’s at last time to wheel out your shopping cart.

476

E-Commerce

The Shopping Car t

The shopping cart is a simple enough control in principle, but until ASP.NET 2.0, it has been an awkward feature to create. The reason is this — how do you go about remembering which items are stored in the cart? The quick answer is state. State management, though, has never been quite as straightforward as it perhaps should be. Chapter 14 looks at sessions and state in detail, but we need to talk about it briefly here.

It’s not a new feature and to be fair, it’s been going on behind the scenes throughout this book, because every page contains a ViewState control that holds an encrypted version of each page’s control contents. However, this is squared against the fact that the Internet is stateless, and every time you move from page to page, the web server acts like a goldfish — asking the same question, “Who are you?” So you must do the remembering for the web server.

Previously, in ASP.NET 1.1, you could go about remembering the items in the cart in one of two common ways. Either you could create a cart and stick the whole contents of the cart in a Session object, and lose the list of items every time someone logged out and back in again, or alternatively you could create a shopping cart item in the database, and then be tied to updating the database each time you added something to the cart. The advantage of the second approach is of course that if you lost your Internet connection suddenly when you came to log back in, you would still have the contents of the cart. This is particularly useful if you’ve just spent an hour assembling the weekly shop, only to have to endure your ISP’s 0.01% downtime at that crucial point. Of course, the first approach could make use of cookies so that it could link back to your shopping cart if you logged on again, but then this would rely on a whole membership system, so you can see how suddenly your nice small shopping cart becomes a rather larger and more complex shopping cart and membership system.

ASP.NET 2.0 is able to take some of the advantages from both approaches (remembering the between connections) while leaving at home some of the awkwardness (constant database access, needing to log on as a member before you can use the shopping cart). It does this by making use of the new profiles features that you looked at in Chapter 11. You’ll see how you can use this as you build your shopping cart control. First, though, you need to build the object that is going to form the foundations of your shopping cart’s memory.

The Shopping Object

You’re going to create an object that can store your items. You start again at the drawing board by creating a design. The first thing to mention is that your shopping object has to look after two things: the items in the cart and the cart itself. Therefore, you’re going to need two objects:

CartItem

ShoppingCart

Both merit some more in-depth discussion as to what is required.

The CartItem Object

The CartItem object is easiest. Design is often just a case of sitting down with pen and paper and trying to imagine what you as a user would require from a site. A second option is to look at what everyone else is doing. However, it’s probably best to stick to this order when brainstorming, because what you

477