Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 52

Chapter 3

How to develop a multi-page web application

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 1

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 applications: App_Code and App_Data. Describe two ways that you can use an existing class with a new web application.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 2

Objectives (continued)
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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 3

The design of the Order page

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 4

The design of the Cart page

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 5

The Solution Explorer for the Shopping Cart application

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 6

Special folders used by the Shopping Cart application


App_Code App_Data

User folder used by the Shopping Cart application


Images

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 7

Adding a new class to the App_Code folder

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 8

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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 9

Adding a new web form

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 10

A web form file being renamed in the Solution Explorer window

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 11

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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 12

Two methods for displaying 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")

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 13

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; } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 14

Statements that use absolute URLs


Response.Redirect("http://www.murach.com/Default.aspx") Response.Redirect("http://www.murach.com/Books/Search.aspx")

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 15

Statements that use relative URLs that are based on the current directory
Response.Redirect("Checkout.aspx") Response.Redirect("Login/Register.aspx")

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 16

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")

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 17

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"

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 18

The Configure Data Source dialog box

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 19

The Configure Data Source wizard

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 20

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>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 21

The Data Source Configuration Wizard dialog box

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 22

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>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 23

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

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 24

How ASP.NET maintains the state of a session


Client
First HTTP request: The browser requests a page. ASP.NET creates a session state object and assigns an ID for the session. Browser

Server

Web server

First HTTP response: The server returns the requested page along with the session ID.

Browser

Session ID Next HTTP request: The browser requests another page. The server uses the session ID included in the request to associate the browser with the correct session state object.

Web server

Browser

Session ID

Web server

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 25

Session state concepts


For each user session, ASP.NET creates a session state object. The session state object includes a session ID thats 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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 26

Typical uses for session state


To keep information about the user, such as the users 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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 27

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)

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 28

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");

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 29

Retrieving the value of a session state item from a class that doesnt inherit System.Web.UI.Page
SortedList cart = (SortedList) HttpContext.Current.Session["Cart"];

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 30

The code for the Product class


using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

/// <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; }
Murachs ASP.NET 3.5/C#, C3 2008, Mike Murach & Associates, Inc. Slide 31

The code for the CartItem class


using using using using using using using using using using using System; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 32

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; } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 33

The aspx file for the Order page (Order.aspx)


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Order.aspx.cs" Inherits="Order" %> <!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 id="Head1" runat="server"> <title>Chapter 3: Shopping Cart</title> <style type="text/css"> .style1 { width: 250px; } .style2 { width: 20px; } </style> </head>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 34

The aspx file for the Order page (cont.)


<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>&nbsp; <asp:DropDownList ID="ddlProducts" runat="server" DataSourceID="AccessDataSource1" DataTextField="Name" DataValueField="ProductID" Width="150px" AutoPostBack="True"> </asp:DropDownList> <asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/Halloween.mdb" SelectCommand="SELECT [ProductID], [Name], [ShortDescription], [LongDescription], [ImageFile], [UnitPrice] FROM [Products] ORDER BY [Name]">

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 35

The aspx file for the Order page (cont.)


</asp:AccessDataSource><br /> <table> <tr> <td class="style1"> <asp:Label ID="lblName" runat="server" style="font-weight: 700; font-size: larger"> </asp:Label> </td> <td class="style2" rowspan="4"></td> <td rowspan="4" valign="top"> <asp:Image ID="imgProduct" runat="server" Height="200px" /> </td> </tr>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 36

The aspx file for the Order page (cont.)


<tr> <td class="style1"> <asp:Label ID="lblShortDescription" runat="server"> </asp:Label> </td> </tr> <tr> <td class="style1"> <asp:Label ID="lblLongDescription" runat="server"> </asp:Label> </td> </tr> <tr> <td class="style1"> <asp:Label ID="lblUnitPrice" runat="server" style="font-weight: 700; font-size: larger"> </asp:Label>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 37

The aspx file for the Order page (cont.)


<asp:Label ID="Label2" runat="server" Text="each" style="font-weight: 700; font-size: larger"> </asp:Label> </td> </tr> </table> <br /> <asp:Label ID="Label3" runat="server" Text="Quantity:" Width="80px"></asp:Label> <asp:TextBox ID="txtQuantity" runat="server" Width="80px"> </asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtQuantity" Display="Dynamic" ErrorMessage="Quantity is a required field."> </asp:RequiredFieldValidator>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 38

The aspx file for the Order page (cont.)


<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" OnClick="btnAdd_Click" />&nbsp; <asp:Button ID="btnCart" runat="server" CausesValidation="False" PostBackUrl="~/Cart.aspx" Text="Go to Cart" /> </div> </form> </body> </html>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 39

The code-behind file for the Order page (Order.aspx.cs)


using using using using using using using using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class Order : System.Web.UI.Page { private Product selectedProduct;

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 40

The code-behind file for the Order page (cont.)


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; }

Murachs ASP.NET 3.5/C#, C3

2008, 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; }

Murachs ASP.NET 3.5/C#, C3

2008, 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"); } }

Murachs ASP.NET 3.5/C#, C3

2008, 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"]; } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 44

The aspx file for the Cart page (Cart.aspx)


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cart.aspx.cs" Inherits="Cart" %> <!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>Chapter 3: Shopping Cart</title> <style type="text/css"> .style1 { width: 286px; height: 153px; } .style2 { height: 153px; } </style> </head>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 45

The aspx file for the Cart page (cont.)


<body> <form id="form1" runat="server"> <div> <asp:Image ID="Image1" runat="server" ImageUrl="~/Images/banner.jpg" /><br /><br /> Your shopping cart:<br /> <table cellpadding="0" cellspacing="0"> <tr> <td class="style1"> <asp:ListBox ID="lstCart" runat="server" Height="135px" Width="267px"></asp:ListBox></td> <td class="style2"> <asp:Button ID="btnRemove" runat="server" Text="Remove Item" Width="100px" OnClick="btnRemove_Click" /> <br /><br />

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 46

The aspx file for the Cart page (cont.)


<asp:Button ID="btnEmpty" runat="server" Text="Empty Cart" Width="100px" OnClick="btnEmpty_Click" /></td> </tr> </table><br /> <asp:Button ID="btnContinue" runat="server" PostBackUrl="~/Order.aspx" Text="Continue Shopping" />&nbsp; <asp:Button ID="btnCheckOut" runat="server" Text="Check Out" OnClick="btnCheckOut_Click" /> <br /><br /> <asp:Label ID="lblMessage" runat="server" ForeColor="Red" EnableViewState="False"></asp:Label> </div> </form> </body> </html>

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 47

The code-behind file for the Cart page (Cart.aspx.cs)


using using using using using using using using using using using using System; System.Collections; System.Configuration; System.Data; System.Linq; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.HtmlControls; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Xml.Linq;

public partial class Cart : System.Web.UI.Page { private SortedList cart;

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 48

The code-behind file for the Cart page (cont.)


protected void Page_Load(object sender, EventArgs e){ this.GetCart(); if (!IsPostBack) this.DisplayCart(); } 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()); } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 49

The code-behind file for the Cart page (cont.)


protected void btnRemove_Click( object sender, EventArgs e){ if (cart.Count > 0) { if (lstCart.SelectedIndex > -1) { cart.RemoveAt(lstCart.SelectedIndex); this.DisplayCart(); } else { lblMessage.Text = "Please select the item " + "you want to remove."; } } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 50

The code-behind file for the Cart page (cont.)


protected void btnEmpty_Click( object sender, EventArgs e){ cart.Clear(); lstCart.Items.Clear(); } protected void btnCheckOut_Click( object sender, EventArgs e){ lblMessage.Text = "Sorry, that function " + "hasn't been implemented yet."; } }

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 51

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.

Murachs ASP.NET 3.5/C#, C3

2008, Mike Murach & Associates, Inc.

Slide 52

You might also like