Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 6 docx

70 460 0
Beginning ASP.NET 2.0 E-Commerce in C# 2005 From Novice to Professional PHẦN 6 docx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Darie-Watson_4681C09.fm Page 329 Tuesday, September 20, 2005 7:28 AM CHAPTER ■ CREATING A CUSTOM SHOPPING CART // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@CartID"; param.Value = shoppingCartId; param.DbType = DbType.String; param.Size = 36; comm.Parameters.Add(param); // return the result table return Decimal.Parse(GenericDataAccess.ExecuteScalar(comm)); } Implementing the Presentation Tier Okay, now that the foundation functionality is in place, you can add the presentation tier bits Building the user interface for the shopping cart functionality involves the following major steps: • Creating Add to Cart buttons (refer to Figure 9-2) • Showing shopping cart summary information in catalog pages (refer to Figure 9-2) • Creating the actual shopping cart page (refer to Figure 9-1) • Allowing the visitor to update product quantities in the shopping cart • Implementing “Continue Shopping” functionality Let’s deal with these tasks one by one Creating the Add to Cart Buttons You can choose to have Add to Cart buttons only in the products details pages (Product.aspx), in the product listings (ProductsList.ascx), or in both Follow the steps in the following exercise to add your buttons Exercise: Creating the Add to Cart Buttons If you implemented the PayPal shopping cart in Chapter 7, you now need to remove the PayPal Add to Cart buttons from Product.aspx Open the file in HTML View and remove the following code: Then remove the associated code from the PopulateControls method in Product.aspx.cs: // Create the "Add to Cart" PayPal link string link = "JavaScript: OpenPayPalWindow(\"https://www.paypal.com/ 329 Darie-Watson_4681C09.fm Page 330 Tuesday, September 20, 2005 7:28 AM 330 CHAPTER ■ CREATING A CUSTOM SHOPPING CART cgi-bin/webscr" + "?cmd=_cart" + // open shopping cart command "&business=youremail@yourserver.com" + // your PayPal account "&item_name=" + pd.Name + // product name "&amount=" + String.Format("{0:0.00}", pd.Price) + // product price "¤cy=USD" + // currency "&add=1" + // quantity to add to the shopping cart "&return=www.yourwebsite.com" + // return address "&cancel_return=www.yourwebsite.com\")"; // cancel return address) // Encode the link characters to be included in HTML file string encodedLink = Server.HtmlEncode(link); // Set the link of the HTML Server Control addToCartLink.HRef = encodedLink; Add the following style to BalloonShop.css You’ll use it for your Add to Cart buttons .SmallButtonText { color: Black; font-family: Verdana, Helvetica, sans-serif; font-size: 10px; } Add a button to the ItemTemplate of the DataList in ProductsList.ascx, just below the product price You can see the HTML code in the following snippet, but keep in mind that you can use the Edit Template feature in Design View to generate at least part of the code In any case, make sure you have this button in the ItemTemplate: Price: ■Note Clicking a button in a DataList fires the DataList’s ItemCommand event In the event handler, you read the CommandArgument of the button, which contains the ID of the product that needs to be added to the shopping cart Darie-Watson_4681C09.fm Page 331 Tuesday, September 20, 2005 7:28 AM CHAPTER ■ CREATING A CUSTOM SHOPPING CART Switch ProductsList.ascx to Design View, select the DataList control, and use the Properties window to add the list’s ItemCommand event handler Complete the generated code with the following code: // fires when an Add to Cart button is clicked protected void list_ItemCommand(object source, DataListCommandEventArgs e) { // The CommandArgument of the clicked Button contains the ProductID string productId = e.CommandArgument.ToString(); // Add the product to the shopping cart ShoppingCartAccess.AddItem(productId); } Now add the same functionality to Product.aspx Open Product.aspx and add the following button at the bottom of the page (note that this new button doesn’t have the CommandArgument property set—this button isn’t part of a DataList, so you don’t need that kind of functionality this time) Switch to Design View and double-click the button to have its Click event handler generated by Visual Web Developer Complete the method signature with the following code: // Add the product to cart protected void addToCartButton_Click(object sender, EventArgs e) { // Retrieve ProductID from the query string string productId = Request.QueryString["ProductID"]; // Add the product to the shopping cart ShoppingCartAccess.AddItem(productId); } How It Works: The Add to Cart Buttons After making the changes, build the project (Ctrl+Shift+B) and then load the site to make sure the buttons appear okay Now click the Add to Cart button on one of the products on the site If you don’t get any errors, the product was probably successfully added to the shopping cart; right now, you can’t see this in the web site, because you still need to implement functionality for viewing the shopping cart The ItemCommand event is raised by the DataList when one of its buttons is clicked The CommandArgument parameter of the Add to Cart buttons is populated with the product ID from the database This ID is read from the ItemCommand event handler, which passes it to ShoppingCart.AddProduct to have it added to the database Showing the Shopping Cart Summary The shopping cart summary is implemented as a Web User Control named CartSummary.ascx You’ll use this control in the BalloonShop.master Master Page, so it shows up in every page that implements it However, you’ll write a bit of code in your control to make sure it doesn’t also 331 Darie-Watson_4681C09.fm Page 332 Tuesday, September 20, 2005 7:28 AM 332 CHAPTER ■ CREATING A CUSTOM SHOPPING CART appear in the shopping cart page, because you don’t want to show both the cart and its summary on the same page Exercise: Showing the Shopping Cart Summary Let’s start with the simple details Add the following styles to BalloonShop.css: CartSummary { border-right: #0468a4 2px solid; border-top: #0468a4 2px solid; border-left: #0468a4 2px solid; border-bottom: #0468a4 2px solid; background-color: snow; font-family: Arial; font-size: 9pt; color: Navy; padding-top: 3px; padding-left: 2px; padding-bottom: 5px; } a.CartLink { color: Black; font-family: Arial; text-decoration: none; font-size: 12px; } a.CartLink:hover { color: Red; } Add a new Web User Control to your UserControls folder, named CartSummary.ascx Make sure the language is Visual C# and that the Place code in separate file check box is checked Add the following code to CartSummary.ascx: x Darie-Watson_4681C09.fm Page 333 Tuesday, September 20, 2005 7:28 AM CHAPTER ■ CREATING A CUSTOM SHOPPING CART Total: Go to the control’s code-behind file (ShoppingCart.ascx.cs) and add the Page_Prerender function, along with its PopulateControls helper function, like this: // fill cart summary contents in the PreRender stage protected void Page_PreRender(object sender, EventArgs e) { PopulateControls(); } // fill the controls with data private void PopulateControls() { // get the items in the shopping cart DataTable dt = ShoppingCartAccess.GetItems(); // if the shopping cart is empty if (dt.Rows.Count == 0) { cartSummaryLabel.Text = "Your shopping cart is empty."; totalAmountLabel.Text = String.Format("{0:c}", 0); viewCartLink.Visible = false; list.Visible = false; } else // if the shopping cart is not empty { // populate the list with the shopping cart contents list.Visible = true; list.DataSource = dt; list.DataBind(); // set up controls cartSummaryLabel.Text = "Cart summary "; viewCartLink.Visible = true; // display the total amount decimal amount = ShoppingCartAccess.GetTotalAmount(); totalAmountLabel.Text = String.Format("{0:c}", amount); } } 333 Darie-Watson_4681C09.fm Page 334 Tuesday, September 20, 2005 7:28 AM 334 CHAPTER ■ CREATING A CUSTOM SHOPPING CART Because you’ll include the shopping cart summary control in the Master Page, normally it will show up in every page of your web site If you don’t want your shopping cart summary to show up when the visitor is viewing the shopping cart page, add the following code to the CartSummary class in CartSummary.ascx.cs: // we don't want to display the cart summary in the shopping cart page protected void Page_Init(object sender, EventArgs e) { // get the current page string page = Request.AppRelativeCurrentExecutionFilePath; // if we're in the shopping cart, don't display the cart summary if (String.Compare(page, "~/ShoppingCart.aspx", true) == 0) this.Visible = false; else this.Visible = true; } The tough part’s over now Build the project to ensure everything compiles okay Open BalloonShop.master in Source View and remove the code of the OpenPayPalWindow JavaScript function, which is no longer necessary: Also in BalloonShop.master, remove the code that generates the PayPal View Cart button:

Switch BallonShop.master to Design View and then drag CartSummary.ascx from the Solution Explorer to BalloonShop.master as shown in Figure 9-7 10 Execute the project to ensure the shopping cart summary shows up as expected Just don’t expect the view details link to work, because you haven’t implemented the ShoppingCart.aspx file yet Darie-Watson_4681C09.fm Page 335 Tuesday, September 20, 2005 7:28 AM CHAPTER ■ CREATING A CUSTOM SHOPPING CART Figure 9-7 Adding the shopping cart summary control to the Master Page How It Works: The Shopping Cart Summary The important bit to understand here is the way we used the Page_PreRender method to populate the control with data We used Page_PreRender instead of the Load event, because Load fires before the Click event of the Add to Cart buttons, so the summary is updated before—not after—the cart is updated PreRender, on the other hand, fires later in the control life cycle, so we used it to ensure that the cart summary is properly updated To learn more about the life cycle of ASP.NET controls, see an advanced ASP.NET book Displaying the Shopping Cart Finally, you’ve arrived at the shopping cart, your primary goal for this chapter The shopping cart is a Web Form named ShoppingCart.aspx, based on the BalloonShop.master Master Page Follow the steps in the next exercise to build your shopping cart page 8213592a117456a340854d18cee57603 335 Darie-Watson_4681C09.fm Page 336 Tuesday, September 20, 2005 7:28 AM 336 CHAPTER ■ CREATING A CUSTOM SHOPPING CART Exercise: Implementing the Shopping Cart Before starting to work on the shopping cart, let’s deal with a simple detail first Add this style to your BalloonShop.css file .ShoppingCartTitle { color: Red; font-family: Verdana, Helvetica, sans-serif; font-size: 16px; } Right-click the project name in Solution Explorer and click Add New Item Select the Web Form template, write ShoppingCart.aspx for its name, make sure the language is Visual C#, and select the two check boxes (Place code in separate file and Select master page), as shown in Figure 9-8 Click Add Figure 9-8 Creating the ShoppingCart.aspx Web Form Choose the BalloonShop.master file in the dialog box that opens and click OK If you prefer to work in Design View, create a form as shown in Figure 9-9, and set the controls’ properties as shown in Table 9-1 Darie-Watson_4681C09.fm Page 337 Tuesday, September 20, 2005 7:28 AM CHAPTER ■ CREATING A CUSTOM SHOPPING CART Figure 9-9 ShoppingCart.aspx in Design View Table 9-1 Control Properties in ShoppingCart.ascx Control Type ID Property Text Property CssClass Property Label titleLabel Your Shopping Cart ShoppingCartTitle Label statusLabel (empty) AdminPageText GridView grid Label totalAmountLabel Button updateButton Update Quantities ButtonText Button continueShoppingButton Continue Shopping ButtonText ProductPrice Feel free to play with the control’s look to customize it according to your preferences The source code of your page should look something like this: Total amount: Now it’s time to deal with the GridView control Set its AutoGenerateColumns property to false, DataKeyNames to ProductID, Width to 100%, and BorderWidth to 0px In Design View, select the GridView, click the Smart Link, and choose Add New Column to add the grid columns listed in Table 9-2 Table 9-2 Setting the Properties of the GridView Control Column Type Header Text Data Field Other Properties BoundField Product Name Name Read Only BoundField Price Price Read Only TemplateField Quantity BoundField Subtotal Subtotal Read Only ButtonField Command name: Delete Text: Delete Button type: Button Darie-Watson_4681C10.fm Page 384 Tuesday, September 20, 2005 4:52 AM 384 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS CREATE PROCEDURE OrderMarkVerified (@OrderID int) AS UPDATE Orders SET Verified = WHERE OrderID = @OrderID OrderMarkCompleted OrderMarkCompleted is called when the administrator clicks the Mark this Order as Completed button It not only sets the Completed bit to but also updates the DateShipped field because an order is completed just after the shipment has been done CREATE PROCEDURE OrderMarkCompleted (@OrderID int) AS UPDATE Orders SET Completed = 1, DateShipped = GETDATE() WHERE OrderID = @OrderID OrderMarkCanceled OrderMarkCanceled is called when the administrator clicks the Mark this Order as Canceled button CREATE PROCEDURE OrderMarkCanceled (@OrderID int) AS UPDATE Orders SET Canceled = WHERE OrderID = @OrderID The Business Tier Methods Apart from the usual methods that pass data back and forth between the user interface and the database stored procedures, you’ll create a struct named OrderInfo Instances of this struct store information about one order and are used to pass order information from the businesstier methods to the presentation tier You learned from the previous chapters, when you built similar structures, that the code looks cleaner when using such a structure instead of passing a DataTable or a DataRow object to the presentation tier The OrderInfo Struct Although you can add this struct to any of the existing files in the App_Code folder (or you can even create a new file for it if you prefer), for consistency and clarity you should add the OrderInfo struct at the beginning of the OrdersAccess.cs file, after the using statements and before the OrdersAccess class 8213592a117456a340854d18cee57603 Darie-Watson_4681C10.fm Page 385 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS /// /// Wraps order data /// public struct OrderInfo { public int OrderID; public decimal TotalAmount; public string DateCreated; public string DateShipped; public bool Verified; public bool Completed; public bool Canceled; public string Comments; public string CustomerName; public string ShippingAddress; public string CustomerEmail; } After this class is in place, add the following methods to the OrdersAccess class: • GetInfo • GetDetails • Update • MarkVerified • MarkCompleted • MarkCanceled GetInfo This method gets information related to a particular order from the database and saves the data into an OrderInfo object, which is then returned // Retrieve order information public static OrderInfo GetInfo(string orderID) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderGetInfo"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderID; param.DbType = DbType.Int32; comm.Parameters.Add(param); 385 Darie-Watson_4681C10.fm Page 386 Tuesday, September 20, 2005 4:52 AM 386 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // obtain the results DataTable table = GenericDataAccess.ExecuteSelectCommand(comm); DataRow orderRow = table.Rows[0]; // save the results into an OrderInfo object OrderInfo orderInfo; orderInfo.OrderID = Int32.Parse(orderRow["OrderID"].ToString()); orderInfo.TotalAmount = Decimal.Parse(orderRow["TotalAmount"].ToString()); orderInfo.DateCreated = orderRow["DateCreated"].ToString(); orderInfo.DateShipped = orderRow["DateShipped"].ToString(); orderInfo.Verified = bool.Parse(orderRow["Verified"].ToString()); orderInfo.Completed = bool.Parse(orderRow["Completed"].ToString()); orderInfo.Canceled = bool.Parse(orderRow["Canceled"].ToString()); orderInfo.Comments = orderRow["Comments"].ToString(); orderInfo.CustomerName = orderRow["CustomerName"].ToString(); orderInfo.ShippingAddress = orderRow["ShippingAddress"].ToString(); orderInfo.CustomerEmail = orderRow["CustomerEmail"].ToString(); // return the OrderInfo object return orderInfo; } GetDetails GetDetails returns the order details of the specified order // Retrieve the order details (the products that are part of that order) public static DataTable GetDetails(string orderID) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderGetDetails"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderID; param.DbType = DbType.Int32; comm.Parameters.Add(param); // return the results DataTable table = GenericDataAccess.ExecuteSelectCommand(comm); return table; } Update This stored procedure updates an order and is called when the Update button in OrderDetailsAdmin is clicked It receives the order details as an OrderInfo parameter and saves them to the database Darie-Watson_4681C10.fm Page 387 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // Update an order public static void Update(OrderInfo orderInfo) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderUpdate"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderInfo.OrderID; param.DbType = DbType.Int32; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@DateCreated"; param.Value = orderInfo.DateCreated; param.DbType = DbType.DateTime; comm.Parameters.Add(param); // The DateShipped parameter is sent only if data is available if (orderInfo.DateShipped.Trim() != "") { param = comm.CreateParameter(); param.ParameterName = "@DateShipped"; param.Value = orderInfo.DateShipped; param.DbType = DbType.DateTime; comm.Parameters.Add(param); } // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@Verified"; param.Value = orderInfo.Verified; param.DbType = DbType.Byte; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@Completed"; param.Value = orderInfo.Completed; param.DbType = DbType.Byte; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@Canceled"; param.Value = orderInfo.Canceled; param.DbType = DbType.Byte; comm.Parameters.Add(param); 387 Darie-Watson_4681C10.fm Page 388 Tuesday, September 20, 2005 4:52 AM 388 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@Comments"; param.Value = orderInfo.Comments; param.DbType = DbType.String; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@CustomerName"; param.Value = orderInfo.CustomerName; param.DbType = DbType.String; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@ShippingAddress"; param.Value = orderInfo.ShippingAddress; param.DbType = DbType.String; comm.Parameters.Add(param); // create a new parameter param = comm.CreateParameter(); param.ParameterName = "@CustomerEmail"; param.Value = orderInfo.CustomerEmail; param.DbType = DbType.String; comm.Parameters.Add(param); // return the results GenericDataAccess.ExecuteNonQuery(comm); } MarkVerified The MarkVerified method is called when the Mark this Order as Verified button is clicked and sets the Verified bit of the specified order in the database to // Mark an order as verified public static void MarkVerified(string orderId) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderMarkVerified"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderId; param.DbType = DbType.Int32; comm.Parameters.Add(param); // return the results GenericDataAccess.ExecuteNonQuery(comm); } Darie-Watson_4681C10.fm Page 389 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS MarkCompleted The MarkCompleted method is called when the Mark this Order as Completed button is clicked and sets the Completed bit of the specified order to // Mark an order as completed public static void MarkCompleted(string orderId) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderMarkCompleted"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderId; param.DbType = DbType.Int32; comm.Parameters.Add(param); // return the results GenericDataAccess.ExecuteNonQuery(comm); } MarkCanceled The MarkCanceled method is called when the Mark this Order as Canceled button is clicked and sets the Canceled bit of the specified order to // Mark an order as canceled public static void MarkCanceled(string orderId) { // get a configured DbCommand object DbCommand comm = GenericDataAccess.CreateCommand(); // set the stored procedure name comm.CommandText = "OrderMarkCanceled"; // create a new parameter DbParameter param = comm.CreateParameter(); param.ParameterName = "@OrderID"; param.Value = orderId; param.DbType = DbType.Int32; comm.Parameters.Add(param); // return the results GenericDataAccess.ExecuteNonQuery(comm); } Creating the User Interface Once again, you’ve reached the place where you wrap up all the data-tier and business-tier functionality and package it into a nice-looking user interface You’ll create the OrderDetailsAdmin user control in the following exercise 389 Darie-Watson_4681C10.fm Page 390 Tuesday, September 20, 2005 4:52 AM 390 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS Exercise: Creating the OrderDetailsAdmin Web User Control Right-click the UserControls folder in Solution Explorer and select Add New Item ➤ Web User Control Choose OrderDetailsAdmin.ascx for the name of the new user control Open the control in Design View and populate it as shown in Figure 10-11 The properties for each constituent control are shown in Table 10-5, and the GridView columns are listed in Table 10-6 For the GridView control, you also need to set its AutoGenerateColumns property to False Figure 10-11 OrderDetailsAdmin.ascx in Design View ■Tip When setting controls’ properties, remember that Visual Studio NET allows you to set properties on more than one control at a time—you can select, for example, the TextBox controls on the right and set their Width to 400px, and so on Darie-Watson_4681C10.fm Page 391 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS 391 Table 10-5 Setting Controls’ Properties in OrderDetailsAdmin.ascx Control Type ID Text CssClass Label orderIdLabel Order #000 AdminTitle Label totalAmountLabel (empty) ProductPrice TextBox dateCreatedTextBox AdminPageText 400px TextBox dateShippedTextBox AdminPageText 400px CheckBox verifiedCheck AdminPageText 400px CheckBox completedCheck AdminPageText 400px CheckBox canceledCheck AdminPageText 400px TextBox commentsTextBox AdminPageText 400px TextBox customerNameTextBox AdminPageText 400px TextBox shippingAddressTextBox AdminPageText 400px TextBox customerEmailTextBox AdminPageText 400px Button editButton Edit SmallButtonText 100px Button updateButton Update SmallButtonText 100px Button cancelButton Cancel SmallButtonText 100px Button markVerifiedButton Mark Order as Verified SmallButtonText 305px Button markCompletedButton Mark Order as Completed SmallButtonText 305px Button markCanceledButton Mark Order as Canceled SmallButtonText 305px Label (doesn’t matter) The order contains these items: AdminPageText GridView grid Width 100% Table 10-6 Setting the Fields of the GridView Control Column Type Header Text Data Field Other Properties BoundField Product ID ProductID Read Only BoundField Product Name ProductName Read Only BoundField Quantity Quantity Read Only BoundField Unit Cost Unit Cost Read Only ButtonField Subtotal Subtotal Read Only 8213592a117456a340854d18cee57603 Darie-Watson_4681C10.fm Page 392 Tuesday, September 20, 2005 4:52 AM 392 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS To make sure we’re on the same page, here’s the source code of the control: Total Amount: Date Created: Date Shipped: Verified: Completed: Canceled: Darie-Watson_4681C10.fm Page 393 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS Comments: Customer Name: Shipping Address: Customer Email: 393 Darie-Watson_4681C10.fm Page 394 Tuesday, September 20, 2005 4:52 AM 394 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS Start writing the code-behind logic of OrderDetailsAdmin.ascx by adding a new field named editMode, “transforming” the Page_Load method to Page_PreRender, and adding some code to it: public partial class OrderDetailsAdmin : System.Web.UI.UserControl { // edit mode by default is false private bool editMode = false; // set up the form protected void Page_PreRender(object sender, EventArgs e) { // check if we must display order details if (Session["AdminOrderID"] != null) { // fill constituent controls with data PopulateControls(); // set edit mode SetEditMode(editMode); } else // Hide this.Visible = false; } } Note the use of Session["AdminOrderID"]—this is set in OrdersAdmin.aspx, when the administrator selects an order from the list The OrderDetailsAdmin.ascx reads this value to find out the ID of the order it needs to display details for In the Page_PreRender function, you use two additional methods: PopulateControls, which populates all the controls on the form with data, and SetEditMode, which disables or enables the text boxes and check boxes for editing Add PopulateControls just after Page_PreRender This method gets the order information into an OrderInfo object, which was especially created for this purpose, by calling the GetInfo method of the OrdersAccess class Using the information from that object, the method fills the constituent controls with data At the end, you call OrdersAccess.GetDetails, which returns the products in the specified order Darie-Watson_4681C10.fm Page 395 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // populate the form with data private void PopulateControls() { // obtain order ID from the session string orderId = Session["AdminOrderID"].ToString(); // obtain order info OrderInfo orderInfo = OrdersAccess.GetInfo(orderId); // populate labels and text boxes with order info orderIdLabel.Text = "Displaying Order #" + orderId; totalAmountLabel.Text = String.Format("{0:c}", orderInfo.TotalAmount); dateCreatedTextBox.Text = orderInfo.DateCreated; dateShippedTextBox.Text = orderInfo.DateShipped; verifiedCheck.Checked = orderInfo.Verified; completedCheck.Checked = orderInfo.Completed; canceledCheck.Checked = orderInfo.Canceled; commentsTextBox.Text = orderInfo.Comments; customerNameTextBox.Text = orderInfo.CustomerName; shippingAddressTextBox.Text = orderInfo.ShippingAddress; customerEmailTextBox.Text = orderInfo.CustomerEmail; // by default the Edit button is enabled, and the // Update and Cancel buttons are disabled editButton.Enabled = true; updateButton.Enabled = false; cancelButton.Enabled = false; // Decide which one of the other three buttons // should be enabled and which should be disabled if (canceledCheck.Checked || completedCheck.Checked) { // if the order was canceled or completed markVerifiedButton.Enabled = false; markCompletedButton.Enabled = false; markCanceledButton.Enabled = false; } else if (verifiedCheck.Checked) { // if the order was not canceled but is verified markVerifiedButton.Enabled = false; markCompletedButton.Enabled = true; markCanceledButton.Enabled = true; } else { // if the order was not canceled and is not verified markVerifiedButton.Enabled = true; markCompletedButton.Enabled = false; markCanceledButton.Enabled = true; } 395 Darie-Watson_4681C10.fm Page 396 Tuesday, September 20, 2005 4:52 AM 396 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // fill the data grid with order details grid.DataSource = OrdersAccess.GetDetails(orderId); grid.DataBind(); } Write the SetEditMode method now, which enables or disables edit mode for the information text boxes // enable or disable edit mode private void SetEditMode(bool enable) { dateCreatedTextBox.Enabled = enable; dateShippedTextBox.Enabled = enable; verifiedCheck.Enabled = enable; completedCheck.Enabled = enable; canceledCheck.Enabled = enable; commentsTextBox.Enabled = enable; customerNameTextBox.Enabled = enable; shippingAddressTextBox.Enabled = enable; customerEmailTextBox.Enabled = enable; editButton.Enabled = !enable; updateButton.Enabled = enable; cancelButton.Enabled = enable; } This method receives a bool parameter that specifies whether you enter or exit edit mode When entering edit mode, all text boxes and the Update and Cancel buttons become enabled, while the Edit button is disabled The reverse happens when exiting edit mode (this happens when one of the Cancel and Update buttons is clicked) Now, start implementing the code that allows the administrator to edit order information To make your life easier, first double-click each of the buttons (Edit, Cancel, Update) in Design View to let Visual Studio generate the signatures of the event handlers Here’s the code: // enter edit mode protected void editButton_Click(object sender, EventArgs e) { editMode = true; } // cancel edit mode protected void cancelButton_Click(object sender, EventArgs e) { // don't need to anything, editMode will be set to false by default } // update order information protected void updateButton_Click(object sender, EventArgs e) { Darie-Watson_4681C10.fm Page 397 Tuesday, September 20, 2005 4:52 AM CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // Store the new order details in an OrderInfo object OrderInfo orderInfo = new OrderInfo(); string orderId = Session["AdminOrderID"].ToString(); orderInfo.OrderID = Int32.Parse(orderId); orderInfo.DateCreated = dateCreatedTextBox.Text; orderInfo.DateShipped = dateShippedTextBox.Text; orderInfo.Verified = verifiedCheck.Checked; orderInfo.Completed = completedCheck.Checked; orderInfo.Canceled = canceledCheck.Checked; orderInfo.Comments = commentsTextBox.Text; orderInfo.CustomerName = customerNameTextBox.Text; orderInfo.ShippingAddress = shippingAddressTextBox.Text; orderInfo.CustomerEmail = customerEmailTextBox.Text; // try to update the order try { // Update the order OrdersAccess.Update(orderInfo); } catch (Exception ex) { // In case of an error, we simply ignore it } // Exit edit mode SetEditMode(false); // Update the form PopulateControls(); } ■Note Here we didn’t implement a mechanism to let the administrator know whether the update was successful or failed—if something happens, we just ignore the error You’ve learned various error-handling techniques in this and previous chapters, and you can choose to implement whichever technique you think is best for your application Do the same for the last three buttons: // mark order as verified protected void markVerifiedButton_Click(object sender, EventArgs e) { // obtain the order ID from the session string orderId = Session["AdminOrderID"].ToString(); // mark order as verified OrdersAccess.MarkVerified(orderId); // update the form PopulateControls(); } 397 Darie-Watson_4681C10.fm Page 398 Tuesday, September 20, 2005 4:52 AM 398 CHAPTER 10 ■ DEALING WITH CUSTOMER ORDERS // mark order as completed protected void markCompletedButton_Click(object sender, EventArgs e) { // obtain the order ID from the session string orderId = Session["AdminOrderID"].ToString(); // mark the order as completed OrdersAccess.MarkCompleted(orderId); // update the form PopulateControls(); } // mark order as canceled protected void markCanceledButton_Click(object sender, EventArgs e) { // obtain the order ID from the session string orderId = Session["AdminOrderID"].ToString(); // mark the order as canceled OrdersAccess.MarkCanceled(orderId); // update the form PopulateControls(); } Open OrdersAdmin.aspx in Design View and drag OrderDetailsAdmin.ascx from the Solution Explorer to the bottom of the second place holder, as shown in Figure 10-12 Figure 10-12 Adding OrderDetailsAdmin.ascx to OrdersAdmin.aspx 8213592a117456a340854d18cee57603 ... link characters to be included in HTML file string encodedLink = Server.HtmlEncode(link); // Set the link of the HTML Server Control addToCartLink.HRef = encodedLink; Add the following style to. .. Continue Shopping button next to the existing Add to Cart button, with the following properties: Property Name Property Value ID continueShoppingButton CssClass SmallButtonText Text Continue... Continue Shopping button will redirect her to the main BalloonShop page 345 Darie-Watson_ 468 1C09.fm Page 3 46 Tuesday, September 20, 2005 7:28 AM 3 46 CHAPTER ■ CREATING A CUSTOM SHOPPING CART Administering

Ngày đăng: 09/08/2014, 14:20

Từ khóa liên quan

Mục lục

  • Beginning ASP.NET 2.0 E-Commerce in C# 2005: From Novice to Professional

    • Chapter 10 Dealing with Customer Orders

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan