View
219
Download
0
Category
Preview:
Citation preview
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 1
Chapter 3
How to develop a multi-page
web application
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 2
Objectives
Applied
Given the specifications for a multi-page web application that uses an Access data source to get data, design, code, and test the application.
To transfer to another page within a web application, be able to use the Transfer method, the Redirect method, or cross-page posting.
To refer to pages or other files within an application, be able to use either absolute or relative URLs.
Knowledge
Describe the contents of these special folders for ASP.NET 2.0 applications: App_Code and App_Data.
Describe two ways that you can use an existing class with a new web application.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 3
Objectives (continued)
Knowledge
In general terms, describe the procedure for renaming a web form file as well as the class that contains the code for the web form.
Distinguish between the Transfer method of the HttpServerUtility class, the Redirect method of the HttpResponse class, and cross-page posting.
Distinguish between absolute and relative URLs.
Describe an Access data source.
In general terms, explain how the AccessDataSource, DataView, and DataRowView classes can be used to get data from a data source.
Describe how session state objects, session IDs, and cookies are used to track the state of each user of a web application.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 4
The design of the Order page
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 5
The design of the Cart page
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 6
The Solution Explorer for the Shopping Cart application
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 7
Special folders App_Code
App_Data
User folder Images
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 8
Adding a new class to the App_Code folder
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 9
Two ways to use an existing class Add the class to your web site by copying it from another project.
Add a reference to the class library that contains the class you want.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 11
A web form file being renamed in the Solution Explorer window
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 12
To rename the class for a renamed file… Change the name on the Class statement for the form.
Change the name in the Inherits attribute of the Page directive in the aspx code for the form.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 13
Two methods for transferring to another page The Transfer method of the HttpServerUtility class
The Redirect method of the HttpResponse class
Code that transfers control to another page Server.Transfer("Cart.aspx")
Code that redirects the client to another page Response.Redirect("Cart.aspx")
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 14
Properties and methods for cross-page posting The aspx code for a button <asp:Button ID="btnCart" runat="server" Text="Go to Cart" CausesValidation="False" PostBackUrl="~/Cart.aspx" />
Code that retrieves data from the previous page protected void Page_Load(object sender, EventArgs e) { if (PreviousPage != null) { TextBox txtQuantity = (TextBox) PreviousPage.FindControl("txtQuantity"); lblQuantity.Text = txtQuantity.Text; } }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 15
Statements that use absolute URLs Response.Redirect("http://www.murach.com/Default.aspx")
Response.Redirect("http://www.murach.com/Books/Search.aspx")
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 16
Statements that use relative URLs that are based on the current directory
Response.Redirect("Checkout.aspx")
Response.Redirect("Login/Register.aspx")
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 17
Statements that use relative URLs that navigate up the directory structure
Response.Redirect("../Register.aspx")
Response.Redirect("../../Register.aspx")
Response.Redirect("/Register.aspx")
Response.Redirect("/Login/Register.aspx")
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 18
Server control attributes that use URLs that are based on the root directory of the current web site
PostBackUrl="~/Cart.aspx" ImageUrl="~/Images/banner.jpg"
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 19
The Configure Data Source dialog box
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 20
The Configure Data Source wizard
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 21
The aspx code for an Access data source control <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Halloween.mdb" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [ImageFile], [UnitPrice] FROM [Products] ORDER BY [Name]"> </asp:AccessDataSource>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 22
The Data Source Configuration Wizard dialog box
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 23
The aspx code for a bound drop-down list <asp:DropDownList ID="ddlProducts" Runat="server" Width="150px" AutoPostBack="True" DataSourceID="AccessDataSource1" DataTextField="Name" DataValueField="ProductID" > </asp:DropDownList>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 24
Getting product information from the data source DataView productsTable = (DataView) AccessDataSource1.Select( DataSourceSelectArguments.Empty); productsTable.RowFilter = "ProductID = '" + ddlProducts.SelectedValue + "'"; DataRowView row = (DataRowView) productsTable[0]; Product p = new Product(); p.ProductID = row["ProductID"].ToString(); p.Name = row["Name"].ToString(); p.ShortDescription = row["ShortDescription"].ToString(); p.LongDescription = row["LongDescription"].ToString(); p.UnitPrice = (decimal) row["UnitPrice"]; p.ImageFile = row["ImageFile"].ToString();
Objects used DataView
DataRowView
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 25
How ASP.NET maintains the state of a session
ServerFirst HTTP request:The browser requests a page.ASP.NET creates a sessionstate object and assigns an IDfor the session.
Client
Web server
First HTTP response:The server returns therequested page along with thesession ID.
Next HTTP request:The browser requests anotherpage. The server uses the sessionID included in the request toassociate the browser with thecorrect session state object.
Web server
Web serverBrowser
Browser
Browser Session ID
Session ID
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 26
Session state concepts For each user session, ASP.NET creates a session state object.
The session state object includes a session ID that’s sent back to the browser as a cookie.
The browser automatically returns the session ID cookie to the server with each HTTP request.
The session ID lets the server find the right session state object.
The session state object can be used to store and retrieve items that can be used by any of the pages in the application.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 27
Typical uses for session state To keep information about the user, such as the user’s name or
whether the user has registered.
To save objects the user is working with, such as a shopping cart or a customer record.
To keep track of pending operations, such as what steps the user has completed while placing an order.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 28
Common properties of the HttpSessionState class SessionID
Count
Common indexer of the HttpSessionState class [name]
Common methods of the HttpSessionState class Add(name, value)
Clear
Remove(name)
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 29
Adding to or updating a session state item Session["Cart"] = cart;
Another way to add or update a session state item Session.Add("Cart", cart);
Retrieving the value of a session state item SortedList cart = (SortedList) Session["Cart"];
Removing an item from session state Session.Remove("Cart");
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 30
Retrieving the value of a session state item from a class that doesn’t inherit System.Web.UI.Page
SortedList cart = (SortedList) HttpContext.Current.Session["Cart"];
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 31
The code for the Product class using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for Product /// </summary> public class Product{ public string ProductID; public string Name; public string ShortDescription; public string LongDescription; public decimal UnitPrice; public string ImageFile; }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 32
The code for the CartItem class using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls;
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 33
The code for the CartItem class (cont.) /// <summary> /// Summary description for CartItem /// </summary> public class CartItem { public Product Product; public int Quantity; public string Display() { string displayString = Product.Name + " (" + Quantity.ToString() + " at " + Product.UnitPrice.ToString("c") + " each)"; return displayString; } }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 34
The aspx file for the Order page <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Order.aspx.cs" Inherits="Order" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Chapter 3: Shopping Cart</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/banner.jpg" /><br /><br /> <asp:Label ID="Label1" runat="server" Text="Please select a product:"></asp:Label> <asp:DropDownList ID="ddlProducts" runat="server" Width = "150px" DataSourceID="AccessDataSource1" DataTextField="Name" DataValueField="ProductID" AutoPostBack="True"> </asp:DropDownList>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 35
The aspx file for the Order page (cont.) <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Halloween.mdb" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [ImageFile], [UnitPrice] FROM [Products] ORDER BY [Name]"> </asp:AccessDataSource> <br /> <table> <tr > <td style="width: 250px; height: 22px"> <asp:Label ID="lblName" runat="server" Font-Bold="false" Font-Size="Larger"> </asp:Label> </td> <td style="width: 20px" rowspan="4"> </td>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 36
The aspx file for the Order page (cont.) <td rowspan="4" valign="top"> <asp:Image ID="imgProduct" runat="server" Height="200" /> </td> </tr> <tr> <td style="width: 250px"> <asp:Label ID="lblShortDescription" runat="server"> </asp:Label> </td> </tr> <tr> <td style="width: 250px"> <asp:Label ID="lblLongDescription" runat="server"> </asp:Label> </td> </tr>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 37
The aspx file for the Order page (cont.) <tr> <td style="width: 250px"> <asp:Label ID="lblUnitPrice" runat="server" Font-Bold="true" Font-Size="Larger"> </asp:Label> <asp:Label ID="Label2" runat="server" Text="each" Font-Bold="true" Font-Size="Larger"> </asp:Label> </td> </tr> </table> <br /> <asp:Label ID="Label3" runat="server" Text="Quantity:" Width="80px" BorderWidth = "0px"></asp:Label> <asp:TextBox ID="txtQuantity" runat="server" Width="80px"> </asp:TextBox>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 38
The aspx file for the Order page (cont.) <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage="Quantity is a required field."> </asp:RequiredFieldValidator> <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage="Quantity must range from 1 to 500." MaximumValue="500" MinimumValue="1" Type="Integer"> </asp:RangeValidator><br /><br /> <asp:Button ID="btnAdd" runat="server" Text="Add to Cart" /> <asp:Button ID="btnCart" runat="server" CausesValidation="False" PostBackUrl="~/Cart.aspx" Text="Go to Cart" /> </div>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 39
The code-behind file for the Order page using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections;
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 40
The code-behind file for the Order page (cont.) public partial class Order : System.Web.UI.Page { private Product selectedProduct; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) ddlProducts.DataBind(); selectedProduct = this.GetSelectedProduct(); lblName.Text = selectedProduct.Name; lblShortDescription.Text = selectedProduct.ShortDescription; lblLongDescription.Text = selectedProduct.LongDescription; lblUnitPrice.Text = selectedProduct.UnitPrice.ToString("c"); imgProduct.ImageUrl = "Images/Products/" + selectedProduct.ImageFile; }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 41
The code-behind file for the Order page (cont.) private Product GetSelectedProduct() { DataView productsTable = (DataView) AccessDataSource1.Select( DataSourceSelectArguments.Empty); productsTable.RowFilter = "ProductID = '" + ddlProducts.SelectedValue + "'"; DataRowView row = (DataRowView) productsTable[0]; Product p = new Product(); p.ProductID = row["ProductID"].ToString(); p.Name = row["Name"].ToString(); p.ShortDescription = row["ShortDescription"].ToString(); p.LongDescription = row["LongDescription"].ToString(); p.UnitPrice = (decimal) row["UnitPrice"]; p.ImageFile = row["ImageFile"].ToString(); return p; }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 42
The code-behind file for the Order page (cont.) protected void btnAdd_Click(object sender, EventArgs e) { if (Page.IsValid) { CartItem item = new CartItem(); item.Product = selectedProduct; item.Quantity = Convert.ToInt32(txtQuantity.Text); this.AddToCart(item); Response.Redirect("Cart.aspx"); } }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 43
The code-behind file for the Order page (cont.) private void AddToCart(CartItem item) { SortedList cart = this.GetCart(); string productID = selectedProduct.ProductID; if (cart.ContainsKey(productID)) { CartItem existingItem = (CartItem) cart[productID]; existingItem.Quantity += item.Quantity; } else cart.Add(productID, item); } private SortedList GetCart() { if (Session["Cart"] == null) Session.Add("Cart", new SortedList()); return (SortedList) Session["Cart"]; } }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 44
The aspx file for the Cart page <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cart.aspx.cs" Inherits="Cart" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Chapter 3: Shopping Cart</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/banner.jpg" /><br /><br /> Your shopping cart:<br /> <table style="width: 500px" cellspacing="0" cellpadding="0" border="0"> <tr> <td style="width: 286px; height: 153px"> <asp:ListBox ID="lstCart" runat="server" Width="267px" Height="135px"> </asp:ListBox> </td>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 45
The aspx file for the Cart page (cont.) <td style="height: 153px"> <asp:Button ID="btnRemove" runat="server" Width="100px" Text="Remove Item"/> <br /><br /> <asp:Button ID="btnEmpty" runat="server" Width="100px" Text="Empty Cart" /> </td> </tr> </table> <br /> <asp:Button ID="btnContinue" runat="server" PostBackUrl="~/Order.aspx" Text="Continue Shopping" /> <asp:Button ID="btnCheckOut" runat="server" Text="Check Out" /> <br /><br /> <asp:Label ID="lblMessage" runat="server"> </asp:Label> </div> </form>
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 46
The code-behind file for the Cart page using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Cart : System.Web.UI.Page { private SortedList cart; protected void Page_Load(object sender, EventArgs e){ GetCart(); if (!IsPostBack) this.DisplayCart(); }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 47
The code-behind file for the Cart page (cont.) private void GetCart(){ if (Session["Cart"] == null) Session.Add("Cart", new SortedList()); cart = (SortedList) Session["Cart"]; } private void DisplayCart(){ lstCart.Items.Clear(); CartItem item; foreach (DictionaryEntry entry in cart) { item = (CartItem) entry.Value; lstCart.Items.Add(item.Display()); } }
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 48
Sorted list concepts Each item in a SortedList object is a DictionaryEntry object.
A DictionaryEntry object consists of a key and value.
The Value property of a DictionaryEntry object returns an Object type so it must be cast to the proper type before it can be stored.
Murach’s ASP.NET 2.0/C#, C3 © 2006, Mike Murach & Associates, Inc. Slide 49
The code-behind file for the Cart page (cont.) protected void btnRemove_Click(object sender, EventArgs e){ if (lstCart.SelectedIndex > -1 && cart.Count > 0){ cart.RemoveAt(lstCart.SelectedIndex); this.DisplayCart(); } } protected void btnEmpty_Click(object sender, EventArgs e){ cart.Clear(); lstCart.Items.Clear(); lblMessage.Text = ""; } protected void btnCheckOut_Click(object sender, EventArgs e){ lblMessage.Text = "Sorry, that function hasn't been implemented yet."; } }
Recommended