ASP 编写购物车

合集下载

基于ASP的购物车的设计与实现

基于ASP的购物车的设计与实现

基于ASP购物车的设计与实现摘要:本文利用Session方法设计并实现了一个购物车。

利用Session的功能,可以将购物信息(商品ID和购买数量)存储到Session变量中,Session方法将数据存储在服务器端的Session("cart")中。

Session方法实现的购物车运行稳定,性能良好,一般的在线购物类网站都选择Session+Dictionary方法实现购物车。

关键词:购物车Session Dictionary ASPThe Design and Implemention of ShoppingCartBased on ASPAbstract:In the paper,it designs and implements a shoppingcart by ing Session,we can save shopping information(such as good ID and quantity) into Session variables.Then Session will save the information into Session("cart") at server. shoppingcart by Session can run stability with good performance. Usually,the line shopping sites choose Session+Dictionary to implement the ShoppingCart.Keyword:ShoppingCart Session Dictionary ASP0引言近年来,随着电子商务的迅猛发展,各种类型的电子商务网站大量涌现。

电子商务网站中的购物车一直是各种动态Web编程技术(如ASP,PHP,JSP和.NET等)要解决的首要问题[1]。

ASP 简单购物车

ASP  简单购物车

ASP 简单购物车
在电子商务网站中,购物车是一个最常用的功能,它记录的用户的消费过程,使用户在购买商品的过程中更加方便、快捷。

本次练习使用Session对象来建立一个简单的购物车实例,使读者熟悉Session 对象的具体应用。

具体步骤如下:
(1)创建shopmain.asp页面。

该页面显示购物广场的软件信息,用户可以通过复选框按钮选择自己感兴趣的软件。

单击【放入购物车】按钮就可以提交购买信息。

还可以通过超链接去购买别的商品、查看购物信息等。

具体效果如图3-9所示。

图3-9 软件商品
(2)创建shop2.asp页面。

该页面于shopmain页面相似,显示购物广场的硬件信息,如笔记本,MP3等。

也可以通过单击【放入购物车】按钮就可以提交购买信息,通过超链接去购买别的商品、查看购物信息等。

具体效果如图3-10所示。

(3)在shopmain.asp和shop2.asp页面中,使用Session对象保存用户购买信
象输出消费信息。

使用购物车的效果如图3-11所示。

图3-11 显示购物信息。

ASP.NET购物车(源码下载)

ASP.NET购物车(源码下载)

购物车(源码下载)说明:该实例基于3.5使用Session实现购物车功能,数据库使用SqlServer2005。

商品的分类以及产品的管理功能不在此实现。

希望该实例能对对购物车功能实现不太清楚的开发人员起到抛砖引玉的功效:)。

文中的产品图片来源于互联网。

1、惯例——预览功能产品列表:当点击每个产品下的添加到购物车图片时,页面会转向到ShoppingCart.aspx同时传递一个当前产品的ID 参数。

购物车:根据ID获取数据添加到DataTable,用Session 存储,如果产品ID存在则不添加。

2、Products表设计Product表模拟数据3、数据访问类SqlHelper.cs类图:代码:using System;using System.Data;using System.Data.SqlClient;namespace DAO{public class SqlHelper{//从Web.config中读取数据库连接字符春private String ConnStr =System.Configuration.ConfigurationSettings.AppSettings[" ConnString"];private SqlConnection conn = null;/// <summary>/// 将查询结果集填充到DataTable/// </summary>/// <param name="query">查询T-Sql</param>/// <returns></returns>public DataTable FillDataTable(String query){DataTable dt = new DataTable();using (conn = new SqlConnection(ConnStr)){SqlCommand cmd = new SqlCommand();cmd.Connection = conn;mandText = query;SqlDataAdapter ada = new SqlDataAdapter();ada.SelectCommand = cmd;ada.Fill(dt);}return dt;}/// <summary>/// 将查询结果集填充到DataSet/// </summary>/// <param name="query">查询T-Sql,可以是多个Select语句</param>/// <returns></returns>public DataSet FillDataSet(String query){DataSet ds = new DataSet();using (conn = new SqlConnection(ConnStr)){SqlCommand cmd = new SqlCommand();cmd.Connection = conn;mandText = query;SqlDataAdapter ada = new SqlDataAdapter();ada.SelectCommand = cmd;ada.Fill(ds);}return ds;}/// <summary>/// 执行insert、update、delete、truncate语句/// </summary>/// <param name="commandText">insert、update、delete、truncate语句</param>public void ExecuteNonQuery(String commandText){using (conn = new SqlConnection(ConnStr)){conn.Open();SqlTransaction tran =conn.BeginTransaction();try{SqlCommand cmd = new SqlCommand();cmd.Connection = conn;cmd.Transaction = tran;mandText = commandText;cmd.ExecuteNonQuery();mit();}catch{tran.Rollback();}finally{tran.Dispose();}}}}} using System;using System.Data;using System.Data.SqlClient;namespace DAO{public class SqlHelper{//从Web.config中读取数据库连接字符春private String ConnStr =System.Configuration.ConfigurationSettings.AppSettings[" ConnString"];private SqlConnection conn = null;/// <summary>/// 将查询结果集填充到DataTable/// </summary>/// <param name="query">查询T-Sql</param>/// <returns></returns>public DataTable FillDataTable(String query){DataTable dt = new DataTable();using (conn = new SqlConnection(ConnStr)){SqlCommand cmd = newcmd.Connection = conn;mandText = query;SqlDataAdapter ada = new SqlDataAdapter();ada.SelectCommand = cmd;ada.Fill(dt);}return dt;}/// <summary>/// 将查询结果集填充到DataSet/// </summary>/// <param name="query">查询T-Sql,可以是多个Select语句</param>/// <returns></returns>public DataSet FillDataSet(String query){DataSet ds = new DataSet();using (conn = new SqlConnection(ConnStr)){SqlCommand cmd = newcmd.Connection = conn;mandText = query;SqlDataAdapter ada = new SqlDataAdapter();ada.SelectCommand = cmd;ada.Fill(ds);}return ds;}/// <summary>/// 执行insert、update、delete、truncate语句/// </summary>/// <param name="commandText">insert、update、delete、truncate语句</param>public void ExecuteNonQuery(String commandText){using (conn = new SqlConnection(ConnStr)){conn.Open();SqlTransaction tran =conn.BeginTransaction();try{SqlCommand cmd = new SqlCommand();cmd.Connection = conn;cmd.Transaction = tran;mandText = commandText;cmd.ExecuteNonQuery();mit();}catch{tran.Rollback();}finally{tran.Dispose();}}}}}4、产品列表功能实现ProductList.aspx前台页面DataList:显示产品列表HyperLink:翻页代码:<%@ Page Language="C#"AutoEventWireup="true" CodeFile="ProductList.aspx.cs" Inherits="ProductList" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd" ><html xmlns="/1999/xhtml"><head runat="server"><title>浏览产品列表</title><link href="CSS/buy.css" mce_href="CSS/buy.css" rel="stylesheet" type="text/css" /></head><body><form id="form1" runat="server"><div id="zone"><div align="right" class="divBorder"><a href="shoppingcart.aspx"mce_href="shoppingcart.aspx"><img src="Images/cart.jpg"mce_src="Images/cart.jpg" alt="我的购物车" border="0" title="查看购物车" /></a></div><br /><div align="center" class="divBorder"><asp:DataList ID="dlProducts"runat="server" RepeatColumns="4"RepeatDirection="Horizontal"OnItemDataBound="dlProducts_ItemDataBound" Width="99%"><ItemTemplate><div><asp:Image ID="imgPic" runat="server" /></div><div><%#Eval("ProductName") %></div><div><fontcolor="gray"><s><%#Convert.ToInt32(Eval("MarketPrice")).ToString("c2") %> </s></font><font color="red"><%#Convert.ToInt32(Eval("BuyPrice")).ToString("c2")%>< /font></div><div><ahref='ShoppingCart.aspx?ID=<%# Eval("ID")%>'><imgsrc="Images/addtocart.png"mce_src="Images/addtocart.png" alt="添加到购物车" border="0" title="添加到购物车" /></a></div></ItemTemplate></asp:DataList></div><br /><div class="divBorder"><asp:Label ID="lblCurrentPage" runat="server"></asp:Label>/<asp:Label ID="lblPageCount" runat="server"></asp:Label>页<asp:HyperLink ID="lnkFirst" runat="server">首页</asp:HyperLink><asp:HyperLink ID="lnkPrev" runat="server">上页</asp:HyperLink><asp:HyperLink ID="lnkNext" runat="server">下页</asp:HyperLink><asp:HyperLink ID="lnkLast" runat="server">末页</asp:HyperLink></div></div></form></body></html> <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ProductList.aspx.cs" Inherits="ProductList" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd" ><html xmlns="/1999/xhtml"><head runat="server"><title>浏览产品列表</title><link href="CSS/buy.css" mce_href="CSS/buy.css" rel="stylesheet" type="text/css" /></head><body><form id="form1" runat="server"><div id="zone"><div align="right" class="divBorder"><a href="shoppingcart.aspx"mce_href="shoppingcart.aspx"><img src="Images/cart.jpg"mce_src="Images/cart.jpg" alt="我的购物车" border="0" title="查看购物车" /></a></div><br /><div align="center" class="divBorder"><asp:DataList ID="dlProducts"runat="server" RepeatColumns="4"RepeatDirection="Horizontal"OnItemDataBound="dlProducts_ItemDataBound" Width="99%"><ItemTemplate><div><asp:Image ID="imgPic" runat="server" /></div><div><%#Eval("ProductName") %></div><div><fontcolor="gray"><s><%#Convert.ToInt32(Eval("MarketPrice")).ToString("c2") %> </s></font><font color="red"><%#Convert.ToInt32(Eval("BuyPrice")).ToString("c2")%>< /font></div><div><ahref='ShoppingCart.aspx?ID=<%# Eval("ID")%>'><imgsrc="Images/addtocart.png"mce_src="Images/addtocart.png" alt="添加到购物车" border="0" title="添加到购物车" /></a></div></ItemTemplate></asp:DataList></div><br /><div class="divBorder"><asp:Label ID="lblCurrentPage" runat="server"></asp:Label>/<asp:Label ID="lblPageCount" runat="server"></asp:Label>页<asp:HyperLink ID="lnkFirst" runat="server">首页</asp:HyperLink><asp:HyperLink ID="lnkPrev" runat="server">上页</asp:HyperLink><asp:HyperLink ID="lnkNext" runat="server">下页</asp:HyperLink><asp:HyperLink ID="lnkLast" runat="server">末页</asp:HyperLink></div></div></form></body></html>用到的CSS代码:[css:nogutter] view plaincopyprint?body{font-size:12px;text-align:center;}#zone{margin:0 auto;width:800px;}.divBorder{border-style:dashed;border-width:thin;} body{font-size:12px;text-align:center;}#zone{margin:0 auto;width:800px;}.divBorder{border-style:dashed;border-width:thin;}PS:页面中关于价格的数字颜色和样式,请用CSS实现后台代码:[c-sharp:nogutter] view plaincopyprint?using System;using System.Web.UI.WebControls;using DAO;using System.Data;public partial class ProductList : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){this.BindList();}}private void BindList(){SqlHelper helper = new SqlHelper();PagedDataSource pds = new PagedDataSource();pds.DataSource = helper.FillDataTable("Select * From Products Order By ID DESC").DefaultView;pds.AllowPaging = true;if (Request.QueryString["P"] != null){pds.PageSize =((DataView)pds.DataSource).Table.Rows.Count;btnRedirect.Text = "浏览器发飙了,赶紧回地球吧";}else{pds.PageSize = 6;btnRedirect.Text = "翻页很累,在火星可以显示所有产品";}int CurrentPage;if (Request.QueryString["Page"] != null){CurrentPage =Convert.ToInt32(Request.QueryString["Page"]);}else{CurrentPage = 1;}pds.CurrentPageIndex = CurrentPage - 1;lblCurrentPage.Text = CurrentPage.ToString();lblPageCount.Text = pds.PageCount.ToString();if (!pds.IsFirstPage){lnkPrev.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" +Convert.ToInt32(CurrentPage - 1);lnkFirst.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=1";}if (!pds.IsLastPage){lnkNext.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" + Convert.ToInt32(CurrentPage + 1);lnkLast.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" + pds.PageCount;}dlProducts.DataSource = pds;dlProducts.DataBind();}protected void dlProducts_ItemDataBound(object sender, DataListItemEventArgs e){if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem){DataRowView drv =(DataRowView)e.Item.DataItem;((Image)e.Item.FindControl("imgPic")).ImageUrl ="~/Images/Products/" + drv["PicturePath"].ToString();}}protected void btnRedirect_Click(object sender, EventArgs e){if (btnRedirect.Text == "翻页很累,在火星可以显示所有产品"){Response.Redirect("ProductList.aspx?P=1");}else{Response.Redirect("ProductList.aspx");}}} using System;using System.Web.UI.WebControls;using DAO;using System.Data;public partial class ProductList : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){this.BindList();}}private void BindList(){SqlHelper helper = new SqlHelper();PagedDataSource pds = new PagedDataSource();pds.DataSource = helper.FillDataTable("Select * From Products Order By ID DESC").DefaultView;pds.AllowPaging = true;if (Request.QueryString["P"] != null){pds.PageSize =((DataView)pds.DataSource).Table.Rows.Count;btnRedirect.Text = "浏览器发飙了,赶紧回地球吧";}else{pds.PageSize = 6;btnRedirect.Text = "翻页很累,在火星可以显示所有产品";}int CurrentPage;if (Request.QueryString["Page"] != null){CurrentPage =Convert.ToInt32(Request.QueryString["Page"]);}else{CurrentPage = 1;}pds.CurrentPageIndex = CurrentPage - 1;lblCurrentPage.Text = CurrentPage.ToString();lblPageCount.Text = pds.PageCount.ToString();if (!pds.IsFirstPage){lnkPrev.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" + Convert.ToInt32(CurrentPage - 1);lnkFirst.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=1";}if (!pds.IsLastPage){lnkNext.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" + Convert.ToInt32(CurrentPage + 1);lnkLast.NavigateUrl =Request.CurrentExecutionFilePath + "?Page=" +pds.PageCount;}dlProducts.DataSource = pds;dlProducts.DataBind();}protected void dlProducts_ItemDataBound(object sender, DataListItemEventArgs e){if (e.Item.ItemType == ListItemType.Item ||e.Item.ItemType == ListItemType.AlternatingItem){DataRowView drv =(DataRowView)e.Item.DataItem;((Image)e.Item.FindControl("imgPic")).ImageUrl ="~/Images/Products/" + drv["PicturePath"].ToString();}}protected void btnRedirect_Click(object sender, EventArgs e){if (btnRedirect.Text == "翻页很累,在火星可以显示所有产品"){Response.Redirect("ProductList.aspx?P=1");}else{Response.Redirect("ProductList.aspx");}}}5、购物车功能实现ShoppingCart.aspx前台页面[xhtml:nogutter] view plaincopyprint?<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ShoppingCart.aspx.cs"Inherits="ShoppingCart" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd" ><html xmlns="/1999/xhtml"><head runat="server"><title>我的购物车</title><link href="CSS/buy.css" mce_href="CSS/buy.css" rel="stylesheet" type="text/css" /><mce:script type="text/javascript"><!--//点击+号图,数量+1function Plus(obj) {obj.value = parseInt(obj.value) + 1; }//数量-1function Reduce(obj) {if (obj.value > 1) {obj.value = obj.value - 1;}}//替换txtAmount文本框非整数的输入//数据整个不合法时置1function CheckValue(obj) {var v = obj.value.replace(/[^/d]/g, '');if (v == '' || v == 'NaN') {obj.value = "1";}else {obj.value = v;}}// --></mce:script></head><body><form id="form1" runat="server"><div id="zone"><div align="left" class="divBorder"><img src="Images/back.jpg"mce_src="Images/back.jpg"onclick="javascript:location.href='ProductList.aspx';"style="cursor: hand" mce_style="cursor: hand" alt="返回产品列表" border="0" title="返回产品列表" /><img src="Images/cart_001.gif"mce_src="Images/cart_001.gif" alt="我的购物车" /></div><br /><div class="divBorder"><asp:GridView ID="gvCart" runat="server" DataKeyNames="ID" AutoGenerateColumns="False"ShowFooter="True" Width="98%" OnRowDataBound="gvCart_RowDataBound" OnRowDeleting="gvCart_RowDeleting"><Columns><asp:BoundFieldDataField="ProductNo" HeaderText="产品编号"><ItemStyle Width="80px" /></asp:BoundField><asp:BoundFieldDataField="ProductName" HeaderText="产品名称" /><asp:TemplateField HeaderText="产品单价"><ItemStyle Width="80px" /><ItemTemplate><%#Convert.ToInt32(Eval("BuyPrice")).ToString("c2") %></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="数量"><ItemStyle Width="80px" /><ItemTemplate><imgsrc="Images/bag_close.gif"mce_src="Images/bag_close.gif" id="imgReduce" runat="server" /><asp:TextBoxID="txtAmount" Width="20px" Height="16px"runat="server" Text='<%# Eval("Amount") %>'onkeyup="CheckValue(this)"></asp:TextBox><imgsrc="Images/bag_open.gif"mce_src="Images/bag_open.gif" id="imgPlus"runat="server" /></ItemTemplate></asp:TemplateField><asp:CommandField HeaderText="删除" DeleteText="删除" ShowDeleteButton="true"><ItemStyle Width="30px" /></asp:CommandField></Columns><EmptyDataTemplate>您的购物车中没有任何商品。

【Dreamweaver+ASP】【第13章 网店购物车】

【Dreamweaver+ASP】【第13章 网店购物车】
(13)单击【测试】按钮,如果连接创建成功,将弹出如图 13.11 所示的对话框。
图 13.10 【自定义连接字符串】对话框
图 13.11 连接创建成功提示
(14)单击【确定】按钮,关闭【自定义连接字符串】对话框。返回【应用程序】面板,向导将自
动在其下拉列表中添加一条【conn】的列表选项,如图 13.12 所示。
'定义初始行变量
Dim rs_last
'定义结束行变量
' set the record count rs_total = rs.RecordCount
'获取记录集总数
' set the number of rows displayed on this page
商品展示功能用来显示商品的基本信息,如商品的图片、名称、定价和卖家名称。通过展示功能, 帮助用户选择商品。
13.2.1 商品展示页面设计
商品展示页面读取所有商品信息,并分页显示商品信息。商品展示页面设计如下所示。 (1)打开 Dreamweaver 的设计界面。单击【文件】|【新建】命令,新建一个名为“list.asp”的标 准 ASP 文件。 (2)单击 Dreamweaver【插入】工具栏中【常用】|【表格】命令。在弹出的【表格】对话框中进 行相应设置,在【文档】窗口中插入了一些表格用于定位。 (3)根据实际情况,可以对特定的单元格进行宽度和背景图片的指定,来修饰表格的外观。在此 基础上,再对单元格行适当的排版,录入相应的文字信息具体效果如图 13.14 所示。
·308·
图 13.27 【记录集导航条】对话框
(17)单击【确定】按钮,关闭对话框。Dreamweave 将在文档窗口中自动插入一排用于翻页控制 的导航条,如图 13.28 所示。

ASP.NET 2.0打造购物车和支付系统之一

ASP.NET 2.0打造购物车和支付系统之一

2.0打造购物车和支付系统之一来源:天极软件作者:朱先忠编译2006年10月11日08:30网友评论:0条点击:1719摘要在本系列文章中,我们基于 2.0构建了一个简化的在线购物车和PayPal系统;并通过这个示例,对 2.0中新引入的GridView控件作了深入研究。

到目前为止,我几乎在每一个我参加过的商业C#.net工程中使用了DataGrid 控件;因此,当我第一次听到有关于GridView是如何提高工作效率时,我飞快地试用了它。

DataGrid和GridView都是 2.0中提供的新的控件类,它们允许你快速容易地显示表格式数据;并且当在线观看它们时,它们都能被转换为客户端HTML表格进行显示。

一. 简介这是系列文章的第一篇。

在本篇中,我们将通过一个简单的网上商店示例程序来集中讨论GridView控件的一些用法。

注意,在每一篇文章中我们都使用相同的源文件。

为了观察本文示例演示效果,你只需要把下载内容解压到你的web服务器上一个新的目录并浏览到该目录名即可。

例如,如果你把所有的内容解压到一个你的web服务器根目录下的目录"gridviewshop",并导航到这个目录:/gridviewshop如果一切顺利,那么你应该会看到一个如下图1所示的站点:图1.本系列文章网上商店演示程序快照。

二. GridView如果你已经使用DataGrid实现了你的系统,包括你自己的定制分页与排序方案,那么,你真正不需要考虑更新到GridView;因为从终端效果来看,它们都生成相同的内容(都生成一个HTML表格)。

然而,如果你刚开始开发一个新的系统,那么,我建议你使用GridView,特别是如果你想利用它内置的分页与排序功能的话。

通过在设计时刻设置各种属性,你可以控制GridView从外观到功能等若干方面。

在本系列文章后面,我们将会更为深入地探讨这些方面,通过把一些CSS类指派给表格行和表格列头;当然,还要添加一些事件处理器以便允许用户与每一行数据进行交互。

实验6-1 利用ASP Session实现购物车功能

实验6-1 利用ASP Session实现购物车功能

实验6-1 利用会话实现购物车功能1 在站点下建立一个Global.asa文件,中输入以下的内容(若该文件存在的话,则添加以下的内容):SUB Session_OnStartSession("idcustomer")=""Session("adminname")=""Session("cartIndex")=Cint(0) '用于存放购物车内的货物数ReDim arrcart(50,3)Session("myCart")=arrcart '二维数组用于存放货物名称END SUBSUB Session_OnEndset Session("idCustomer")=Nothingset Session("adminname")=Nothingset Session("cartIndex")=Nothingset Session("myCart")=NothingEND SUB说明:Global.asa 文件是一个可选的文件,它可包含可被 ASP 应用程序中每个页面访问的对象、变量以及方法的声明。

Global.asa 文件须存放于 ASP 应用程序的根目录中,且每个应用程序只能有一个Global.asa 文件。

详细内容参见/asp/asp_globalasa.asp2 建立挑选商品网页mechase.html,内容如下:<html><head><title>挑选商品</title></head><body><form name="form1" method="post" action="addcart.asp"> 图书编号<input type="text" name="idbook" size=3>商品名称<select name="bookname"><option value="数学">数学</option><option value="语文">语文</option><option value="物理">物理</option><option value="化学">化学</option></select>购买数量<input type="text" name="quantity" size=3> <br> <input type="submit" name="submit1" value="放入购物车"> </form></body></html>3 建立放入购物车网页addcart.asp,内容如下:<html><head><title>放入购物车</title></head><body><%arrCart=Session("myCart")CartIndex=Session("cartIndex")count=0for i=0 to CartIndexif arrCart(i,2)<>"" thenif arrCart(i,2)>0 thencount=count+1end ifend ifnext'count中为统计出的购物车中所购商品的总数,用于价格计算idbook=request("idbook")bookname=request("bookname")quantity=request("quantity")if quantity<>"" thenquantity=Cint(quantity)'newprice=查询数据库来计算新的价格if quantity>0 thenarrCart(CartIndex,0)=idbookarrCart(CartIndex,1)=booknamearrCart(CartIndex,2)=quantity'arrCart(CartIndex,3)=newpriceSession("myCart")=arrCartSession("cartIndex")=CartIndex+1response.redirect "showcart.asp" '转到显示购物车内容的网页 end ifelseresponse.write "你没有选择购买数量!"end if%></body></html>。

ASP.NET项目开发教程课件项目六 购物车、订单、内置对象

ASP.NET项目开发教程课件项目六 购物车、订单、内置对象

3. Request对象
Request对象常用方法或属性及说明
说明
获取HTML表单中<from>标记的字段内容 获取URL中参数的值 获取服务器端或客户端的系统信息 获取客户端的浏览器信息 获取客户端浏览器的Cookie信息 获取客户端的安全证书 获取服务器上应用程序虚拟应用程序的根目录路径 获取当前请求的虚拟路径 从Cookie、From、QueryString或ServerVariables集合中获取指定的对象
任务描述
Order.aspx我的订单
任务3 订单信息处理
[任务分析] 1. 添加订单信息 2. profile添加订单详情 3. 修改商品数量 4. 订单详情显
预备知识
本任务是综合运用前面所学知识,完成系统功能。
任务实施
• 步骤1 填写订单页面 • 步骤2 实现订单功能 • 步骤3 订单后台连接数据库操作 • 步骤4 我的订单页面 • 步骤5 实现订单查看功能
任务小结
• 本任务主要实现订单处理功能,实现数据 库的灵活应用。通过学习,我们能掌握对 不同数据表的操作,巩固了数据库知识, 为后面做后台管理打基础。。
任务4 统计网站历史访问总数、在线人数
[任务描述] • 母版页中添加显示网站在线人数和网站历
史访问总数。
任务4 统计网站历史访问总数、在线人数
任务小结
本任务主要是介绍实现用户登录和登录 信息传递,巩固前面知识。
任务3 订单信息处理
[任务描述] • 用户在购物车中提交“结算”时,若用户
已经登录将直接跳到订单信息填写页面, 填写订单信息后单击“提交结算”。就可 将信息写入数据库中。单击“我的订单, 可以看到当前用户的订单信息。
任务描述

asp.net实现购物车详细代码

asp.net实现购物车详细代码

实现购物车详细代码<%@ Page language="c#" Codebehind="shoppingcart.aspx.cs" AutoEventWireup="false" Inherits="myshop.shoppingcart" %><!DOCTYPE HTML PUBLIC "-//W3C// DTD HTML 4.0 Transitional//EN" ><HTML><HEAD><title>shoppingcart</title><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><LINK href="mycss.css" type="text/css" rel="stylesheet"><meta name="vs_defaultClientScript" content="JavaScript"><meta name="vs_targetSchema" content="/intellisense/ie5"></HEAD><body><center><form id="Form1" runat="server"><table width="500" border="0" cellspacing="0" cellpadding="0"><tr><td><asp:DataGrid id="ShoppingCartDlt" runat="server" Width="500" BackColor="white" BorderColor="black" ShowFooter="false" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt" HeaderStyle-BackColor="#cecfd6" AutoGenerateColumns="false" MaintainState="true"><Columns><asp:TemplateColumn HeaderText="删除"><ItemTemplate><center><asp:CheckBox id="chkProductID" runat="server"/></center></ItemTemplate></asp:TemplateColumn><asp:BoundColumn DataField="ProdID" HeaderText="ID"/><asp:BoundColumn DataField="ProName" HeaderText="商品名称"/><asp:BoundColumn DataField="UnitPrice" HeaderText="单价"/><asp:TemplateColumn HeaderText="数量"><ItemTemplate><asp:TextBox id="CountTb" runat="server" Text='<%#DataBinder.Eval( Container.DataItem,"ProdCount" )%>'> </asp:TextBox></ItemTemplate></asp:TemplateColumn><asp:BoundColumn DataField="TotalPrice" HeaderText="⼩计( 元 )"/></Columns></asp:DataGrid></td></tr></table><br><table width="500" border="0" cellspa cing="0" cellpadding="0"><tr><td><asp:Button id="update" runat="server" Text="更新我的购物车" CssClass="button2"/></td><td><asp:Button id="CheckOut" runat="server" Text="结算" CssClass="button5"/><input type="button" name="close2" value="继续购物" onClick="window.close( );return false;" class="button2"></td><td align="right"><br><asp:Label id="label" runat="server" Width="100px" Visible="True" ForeColor="#FF8080" Height="18px"></asp:Label></td></tr></table></form></center></body></HTML>using System;using System.Collections;using ponentModel;using System.Web.SessionState;using System.Web;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Data;using System.Data.OleDb;using System.Configuration;namespace myshop{///<summary>/// shoppingcart 的摘要说明. ///</summary> public class shoppingcart : System.Web.UI.Page{protected System.Web.UI.WebControls.DataGrid ShoppingCartDlt;protected System.Web.UI.WebControls.Button update;protected System.Web.UI.WebControls.Button CheckOut;protected System.Web.UI.HtmlControls.HtmlForm Form1;protected bel label;protected System.Web.UI.WebControls.CheckBox chkProductID;protected System.Web.UI.WebControls.TextBox txtCount;protected System.Web.UI.WebControls.TextBox CountTb;string AddProID;private void Page_Load( object sender, System.EventArgs e ){try{if ( Session["logon"]!="yes" Session["username"]==null ){Response.Redirect( "error.htm" ) ;}}catch{Response.Redirect( "error.htm" ) ;}/////////////查看⽤户是否已经登陆.if( !IsPostBack ){if( Request.Params["mode"]=="view" ) //检测是否为直接查看购物车.{ViewShoppingCart( );Caculator( );if( Request.Params["productID"]!=null Request.Params["productID"]!="" )using System.Web;using System.Web.UI;using System.Web.UI.HtmlControls;using System.Web.UI.WebControls;using System.Data;using System.Data.OleDb;using System.Configuration;namespace myshop{///<summary>/// shoppingcart 的摘要说明. ///</summary> public class shoppingcart : System.Web.UI.Page {protected System.Web.UI.WebControls.DataGrid ShoppingCartDlt;protected System.Web.UI.WebControls.Button update;protected System.Web.UI.WebControls.Button CheckOut;protected System.Web.UI.HtmlControls.HtmlForm Form1;protected bel label;protected System.Web.UI.WebControls.CheckBox chkProductID;protected System.Web.UI.WebControls.TextBox txtCount;protected System.Web.UI.WebControls.TextBox CountTb;string AddProID;private void Page_Load( object sender, System.EventArgs e ){try{if ( Session["logon"]!="yes" Session["username"]==null ){Response.Redirect( "error.htm" ) ;}}catch{Response.Redirect( "error.htm" ) ;}/////////////查看⽤户是否已经登陆.if( !IsPostBack ){if( Request.Params["mode"]=="view" ) //检测是否为直接查看购物车.{ViewShoppingCart( );Caculator( );}if( Request.Params["productID"]!=null Request.Params["productID"]!="" ){AddProID=Request["productID"];UpdateShoppingCart( );Caculator( );}}// 在此处放置⽤户代码以初始化页⾯}public void CreateCartTable( ) //创建购物车{DataSet ds = new DataSet( );DataTable newDT=new DataTable( "CartTable" );ds.Tables.Add( newDT );DataColumn newDC;newDC=new DataColumn( "ProdID",System.Type.GetType( "System.Int32" ) );ds.Tables["CartTable"].Columns.Add( newDC );newDC=new DataColumn( "ProdCount",System.Type.GetType( "System.Int32" ) );newDC.DefaultValue=1;ds.Tables["CartTable"].Columns.Add( newDC );newDC=new DataColumn( "ProName",System.Type.GetType( "System.String" ) );ds.Tables["CartTable"].Columns.Add( newDC );newDC=new DataColumn( "UnitPrice",System.Type.GetType( "System.Double" ) );ds.Tables["CartTable"].Columns.Add( newDC );newDC=new DataColumn( "TotalPrice",System.Type.GetType( "System.Double" ) );ds.Tables["CartTable"].Columns.Add( newDC );newDC=new DataColumn( "IsDeleted",System.Type.GetType( "System.Int32" ) );newDC.DefaultValue=0;// public void WriteShoppingCart( ) 中 newDR[5]="0";⾏,已被注销, ds.Tables["CartTable"].Columns.Add( newDC );Session["myCartTable"]=newDT;ShoppingCartDlt.DataSource=ds.Tables["CartTable"].DefaultView;ShoppingCartDlt.DataBind( );}public void UpdateShoppingCart( ){if( Session["myCartTable"]==null )//Session["myCartTable"]==null{CreateCartTable( );//调⽤函数CreateCartTable( )新建⼀个DataTable WriteShoppingCart( );}//如果购物蓝中已有商品,则需要对购物信息表DataTable进⾏更新,并将其棒定到ShoppingCartDlt WriteShoppingCart( );}}public void ViewShoppingCart( ) //查看购物车{ if( Session["myCartTable"]!=null ){DataTable viewTable=new DataTable( "nowCartTable" );viewTable=( DataTable )Session["myCartTable"];ShoppingCartDlt.DataSource = viewTable.DefaultView;//购物车棒定到ShoppingCartDlt ShoppingCartDlt.DataBind( );}}public void WriteShoppingCart( ){if( Request.Params["mode"]!="view" ) //检查是否是直接查看购物车,如果直接查看,就不再写MYCARTTABLE{DataTable nowTable=new DataTable( "nowCartTable" );nowTable=( DataTable )Session["myCartTable"];int pn=nowTable.Rows.Count;int i=0;bool hasone=false;int nowProdID;while( i<pn && !hasone ){nowProdID=Int32.Parse( nowTable.Rows[i][0].ToString( ) );if( nowProdID==Int32.Parse( AddProID ) ) //判断购物信息表中,是否存有当前放⼊商品. if( nowProdID==Int32.Parse( AddProID ) ) {hasone=true;}else{i++;}}if( hasone ){//如果已有该商品,则 hasone=true,更改该数据⾏ DataRow oldDR;oldDR=nowTable.Rows[i];oldDR["ProdCount"]=Int32.Parse( oldDR["ProdCount"].ToString( ) )+1;oldDR["TotalPrice"]=Int32.Parse( oldDR["ProdCount"].ToString( ) )*Double.Parse( oldDR["UnitPrice"].ToString( ) );}else{//如果没有该商品,在表中新加如⼀⾏. DataRow newDR;double unitp;String strcon="provider=Microsoft.jet.OLEDB.4.0;data Source="+Server.MapPath( ConfigurationSettings.AppSettings["MDBpath2"] )+";";OleDbConnection myConnection = new OleDbConnection( strcon );string strSQL= "select * from pro where product_id="+AddProID+"";OleDbDataAdapter myCommand = new OleDbDataAdapter( strSQL, myConnection );DataSet ds = new DataSet( );myCommand.Fill( ds, "AddP" );newDR=nowTable.NewRow( );newDR[0]=AddProID;newDR[2]=ds.Tables["Addp"].Rows[0]["product_name"].ToString( );unitp=Double.Parse( ds.Tables["AddP"].Rows[0]["product_memprice"].ToString( ) );//会员价 newDR[3]=unitp;newDR[4]=unitp;//第⼀次读库,所以总价格和单价是⼀样的. //newDR[5]="0";nowTable.Rows.Add( newDR );myConnection.Close( );}ShoppingCartDlt.DataSource = nowTable.DefaultView;//将更新后的 DataTable棒定到ShoppingCartDlt ShoppingCartDlt.DataBind( );Session["myCartTable"] = nowTable;//重新保存更新过的DataTable}}public void Caculator( ){if( Session["myCartTable"]!=null ) //购物车是否为空{int h;Double TotalPri;TotalPri=0;DataTable nowTable3=new DataTable( "nowCartTable3" );nowTable3=( DataTable )Session["myCartTable"];if( nowTable3.Rows.Count>0 ) //返回购物车中是否有货物{for( h=0;h<=nowTable3.Rows.Count-1;。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

如今互联网高速发展,人们的生活起居都与网络息息相关,最常见的就是网络购物。

网购以
极大方便人们购物和丰富的购物选择而被人们广泛喜爱。

在我国网上购物从无到有也不过短
短几年时间。

购物车是电子商务网站与用户交互的重要模块,购物网站要完成购买转化率,
除了要有丰富、适合消费者需求的产品外,对于购物车的设计也要做到操作简便、流程清晰、
付款方便等特点。

它的主要作用是临时存放用户的购物信息,用户可以随时增加商品、修改
数量、删除商品等操作。

购物车设计得好与坏,直接决定了用户购买的积极性,对于网站转
化率而言具有举足轻重的意义。

在我国目前主流购物系统中采用ASP、PHP、JSP语言开发。

本论文在设计购物车系统的时选择了ASP技术,这是因为ASP在开发Web程序上具备许多
优势.例如具有很强的简易性、安伞性、自定义性和扩展性,还具有多种性能优良的功能和
高效的可管理性。

购物车的功能实现采用Session对象设计方法。

在代码上采用C#语言编写,
C#拥有C/C++的强大功能以及Visual Basic简易使用的特性具有①通用性,与JA V A等这些
大众语言差不多,易上手②VS编码工具强大,特别是应用式软件,编码速度非常快③封装
的很好,适合初学者等优点。

系统的后台数据库设计采用的是SQL Server2008这是因为我
们考虑到电子商务网站对后台数据处理的各项性能的要求,该数据库对数据的安全性、稳定性、可靠性、易维护性等均较好的满足设计要求,使设计的购物车具有更多的功能。

Nowadays the Internet has a rapid development, people's daily life have a closely relation with internet, the most common is the online-shopping, which is convenient for us and is widely loved by most people for rich shopping choice. It is just several years for online shopping developed from nothing in our country. Shopping cart is the important module between e-commerce sites and users interaction. The shopping website is to complete the purchase conversion, besides have rich, suitable for the consumer demand the product, for the design of the shopping cart it easy operation, flow clear, payment is
convenient wait for a characteristic. Its main effect is temporary storage of users shopping information, user can increase commodity, modify quantity, delete operation commodities, etc. Shopping cart designed to good and bad, and directly determine the users buy's enthusiasm, for the website for conversion are the most important significance. In our country at present the mainstream shopping system USES ASP, PHP, JSP language development. In this paper the design of the shopping cart system to choose ASP technology, this is because in the development of Web program on ASP have many advantages. For example has a strong simplicity, Ann umbrella sex, custom sex and expansibility, also has the variety of excellent performance of functions and efficient management capacity. The realization of the function of the shopping cart by Session object design method. In the code used to write on the C #, C# has the strong function of C/C + + and Visual Basic simple use of characteristics (1) generality, and JAVA these
public language about, accessible (2) VS coding tools powerful, especially the application type software, encoding speed very fast (3) package is very good, is suitable for beginners, etc. The system is designed with the backend database SQL Server2008 this is because we consider
e-commerce sites to the background data processing of various performance requirements, this database in data security and stability, reliability, easy maintenance, etc are better meet the requirement of design, and make the design has the function of the more shopping cart.。

相关文档
最新文档