ASP.NET购物车实现过程详解

所属分类: 网络编程 / ASP.NET 阅读数: 1119
收藏 0 赞 0 分享

本文实例为大家分享了ASP.NET实现购物车的具体代码,供大家参考,具体内容如下

1、 将test数据库附加到数据库管理系统中;数据库中的book_info包含下列数据:

2、 新建一个网站,将images文件夹复制到网站中;

3、 在Default.aspx中,通过DataList控件展示数据库中的所有数据,以行为主序,每行3列,单击购买按钮时,将商品的ID和数量保存到HashTable中,并将HashTable放置到Session中。

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e) 
 { 
  string id = e.CommandArgument.ToString(); 
  Hashtable ht; 
  if (Session["shopcar"] == null) 
  { 
   ht = new Hashtable(); 
   ht.Add(id, 1); 
   Session["shopcar"] = ht; 
  } 
  else 
  { 
   ht = (Hashtable)Session["shopcar"]; 
   if (ht.Contains(id)) 
   { 
    int count = int.Parse(ht[id].ToString()); 
    ht[id] = count + 1; 
    Session["shopcar"] = ht; 
    Response.Write(count + 1); 
   } 
   else 
   { 
    ht.Add(id, 1); 
    Session["shopcar"] = ht; 
   } 
  } 
 } 

4、 在Default.aspx中添加一个超链接,链接到shopcart.aspx,在shopcart.aspx中显示用户购买的商品信息。
提示:

A、在shopcart中先定义下列变量:

Hashtable ht;
 DataTable dt;
 string connstring=@"DataSource=.\SQLEXPRESS;Initial Catalog=test;Integrated Security=True";
 SqlConnection conn;
 SqlCommand cmd;
 SqlDataReader sdr;

B、页面中添加一个GridView。
C、在page_load中,将dt实例化,建立各列。

protected void Page_Load(object sender, EventArgs e)
 {
  dt = new DataTable();
  DataColumn col = new DataColumn();
  col.ColumnName= "id";
  col.DataType =System.Type.GetType("System.String");
  dt.Columns.Add(col);
  col = new DataColumn();
  col.ColumnName= "name";
  col.DataType =System.Type.GetType("System.String");
  dt.Columns.Add(col);
  col = new DataColumn();
  col.ColumnName= "Num";
  col.DataType =System.Type.GetType("System.Int32");
  dt.Columns.Add(col);
  col = new DataColumn();
  col.ColumnName= "price";
  col.DataType =System.Type.GetType("System.Single");
  dt.Columns.Add(col);
  col = new DataColumn();
  col.ColumnName= "Total";
  col.DataType =System.Type.GetType("System.Single");
  dt.Columns.Add(col);
  if (!IsPostBack)
  {
   Bind();
  }
 }
 
 
 public void Bind()
 {
  
 
  if (Session["shopcar"] == null)
  {
   Response.Write("<script>if(confirm('你没有登录')window.location='Default15.aspx';else window.close();</script>");
  }
  else
  {
   ht = (Hashtable)Session["shopcar"];
   foreach (object item in ht.Keys)
   {
    string id = item.ToString();
    int num = int.Parse(ht[item].ToString());
    string sql = "selectbook_name,price from book_info where book_id='" + id + "'";
    conn = new SqlConnection(connstring);
    cmd = new SqlCommand(sql, conn);
    conn.Open();
    sdr =cmd.ExecuteReader();
    if (sdr.HasRows)
    {
     sdr.Read();
     DataRow row = dt.NewRow();
     row["id"] = id;
     row["Num"] = num;
     row["name"] = sdr.GetString(0);
     row["price"] =float.Parse(sdr[1].ToString());
     row["total"] =num*(float.Parse(sdr[1].ToString()));
     dt.Rows.Add(row);
    }
    sdr.Close();
    conn.Close();
        
   }
   GridView1.DataSource = dt.DefaultView;
   GridView1.DataBind();
  }
}

D、这时可以看到用户购买的商品,但不能修改数量,也不能删除。
E、添加修改数量,删除商品功能,在aspx页面中定义GridView中的各列:

 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
   <Columns>
    <asp:BoundField DataField="id" HeaderText="ID" />
    <asp:BoundField DataField="name" HeaderText="名称" />
    <asp:BoundField DataField="price" HeaderText="价格" />
    <asp:TemplateField>   
    <ItemTemplate>
     <asp:TextBox runat="server" ID="textbox1" Text='<%# Eval("Num") %>'
      ontextchanged="textbox1_TextChanged" AutoPostBack="True" ></asp:TextBox>
    </ItemTemplate>   
    </asp:TemplateField>
   <asp:BoundField DataField="total" HeaderText="总计" />
   <asp:TemplateField>
    <ItemTemplate>
    <asp:Button runat="server" ID="button1" CommandArgument='<%# Eval("id") %>'
      Text="删除" onclick="button1_Click" />
    
    </ItemTemplate>
   
   </asp:TemplateField>
   </Columns>   
  </asp:GridView>

F、为GridView中的文本框添加TextChanged事件:

protected void textbox1_TextChanged(object sender, EventArgs e)
 {
  
  Hashtable ht =(Hashtable)Session["shopcar"];
  if (ht == null) return;
  for (int i = 0; i < GridView1.Rows.Count;i++)
  {
   string id =GridView1.Rows[i].Cells[0].Text.ToString();
   Response.Write(id);
   string num = ((TextBox)GridView1.Rows[i].FindControl("textbox1")).Text;
   Response.Write(" "+num+"<br />");
   ht[id] = num;
  }
  Session["shopcar"] = ht;
  Bind();
  
 }

G、为按钮添加单击事件:

protected void button1_Click(object sender, EventArgs e)
 {
  string id = ((Button)sender).CommandArgument;
  Hashtable ht = (Hashtable)Session["shopcar"];
  if (ht == null) return;
  ht.Remove(id);
  Bind();
}

购物车代码:showcart.aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Collections; 
using System.Data; 
using System.Data.SqlClient; 
 
public partial class shopcart : System.Web.UI.Page 
{ 
 Hashtable ht; 
 DataTable dt; 
 string connstr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=F:

\\test.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; 
 SqlConnection conn; 
 SqlCommand cmd; 
 SqlDataReader sdr; 
 protected void Page_Load(object sender, EventArgs e) 
 { 
  dt = new DataTable(); 
  DataColumn col = new DataColumn(); 
  col.ColumnName = "id"; 
  col.DataType = System.Type.GetType("System.String"); 
  dt.Columns.Add(col); 
  col = new DataColumn(); 
  col.ColumnName = "name"; 
  col.DataType = System.Type.GetType("System.String"); 
  dt.Columns.Add(col); 
  col = new DataColumn(); 
  col.ColumnName = "Num"; 
  col.DataType = System.Type.GetType("System.Int32"); 
  dt.Columns.Add(col); 
  col = new DataColumn(); 
  col.ColumnName = "price"; 
  col.DataType = System.Type.GetType("System.Single"); 
  dt.Columns.Add(col); 
  col = new DataColumn(); 
  col.ColumnName = "Total"; 
  col.DataType = System.Type.GetType("System.Single"); 
  dt.Columns.Add(col); 
 
  if (!IsPostBack) 
  { 
   Bind(); 
  } 
 
 } 
 
 public void Bind() 
 { 
  if (Session["shopcar"] == null) 
  { 
   Response.Write("<script>if(confirm('你没有登录')window.location='Default.aspx';else window.close();</script>"); 
  } 
  else 
  { 
   ht = (Hashtable)Session["shopcar"]; 
   foreach (object item in ht.Keys) 
   { 
    string id = item.ToString(); 
 
    int num = int.Parse((ht[item].ToString())); 
    string sql = "select book_name,price from book_info where book_id='" + id + "'"; 
    conn = new SqlConnection(connstr); 
 
    cmd = new SqlCommand(sql, conn); 
    conn.Open(); 
 
    sdr = cmd.ExecuteReader(); 
    if (sdr.HasRows) 
    { 
     sdr.Read(); 
     DataRow row = dt.NewRow(); 
     row["id"] = id; 
     row["Num"] = num; 
     row["name"] = sdr.GetString(0); 
     row["price"] = float.Parse(sdr[1].ToString()); 
     row["total"] = num * (float.Parse(sdr[1].ToString())); 
     dt.Rows.Add(row); 
 
    } 
    sdr.Close(); 
    conn.Close(); 
   } 
  } 
  GridView1.DataSource = dt.DefaultView; 
  GridView1.DataBind(); 
 
 } 
 protected void textbox1_TextChanged(object sender, EventArgs e) 
 { 
  Hashtable ht = (Hashtable)Session["shopcar"]; 
  if (ht == null) return; 
  for (int i = 0; i < GridView1.Rows.Count; i++) 
  { 
   string id = GridView1.Rows[i].Cells[0].Text.ToString(); 
   Response.Write(id); 
   string num = ((TextBox)GridView1.Rows[i].FindControl("textbox1")).Text; 
   Response.Write(" " + num + "<br />"); 
   ht[id] = num; 
  } 
  Session["shopcar"] = ht; 
  Bind(); 
 
 } 
 protected void button1_Click(object sender, EventArgs e) 
 { 
  string id = ((Button)sender).CommandArgument; 
  Hashtable ht = (Hashtable)Session["shopcar"]; 
  if (ht == null) return; 
  ht.Remove(id); 
  Bind(); 
 
 } 
} 

制作一个简单的购物车就是这么简单,大家可以按照我的思路进行创作,在此基础上在添加一些功能。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

更多精彩内容其他人还在看

asp.net 虚方法、抽象方法、接口疑问

asp.net 虚方法、抽象方法、接口疑问等说明。
收藏 0 赞 0 分享

c#  操作符?? null coalescing operator

?? "null coalescing" operator 是c#新提供的一个操作符,这个操作符提供的功能是判断左侧的操作数是否是null,如果是则返回结果是右侧的操作数;非null则返回左侧的操作数。
收藏 0 赞 0 分享

.net 反序题目的详细解答第1/2页

在各种答案,以及平时面试过程中,这道题总归会有一些非常典型的错误发生。其中给老赵的感觉也非常有意思,不知其中的“思路”是否如老赵猜测那样。
收藏 0 赞 0 分享

implicitly convert type 'int' to 'short'的原因与解决方法

implicitly convert type 'int' to 'short'的原因与解决方法
收藏 0 赞 0 分享

比较完整的 asp.net 学习流程

好多朋友想学习后台编程语言,但请注意的事,学习后台是个循序渐进的过程,不可能一下就到位,其实不只是asp.net其它的编程语言都需要下面的一些知识。
收藏 0 赞 0 分享

官网 Ext direct包中.NET版的问题

下载了官网的 Ext direct 包进行研究,发现服务器端返回结果存在一点小问题。
收藏 0 赞 0 分享

C# XML操作 代码大全(读XML,写XML,更新,删除节点,与dataset结合等)第1/2页

C#操作XML(读XML,写XML,更新,删除节点,与dataset结合等),以下就是操作XML的所有方法,相信可以满足很大一部份的使用了。
收藏 0 赞 0 分享

c# 连接字符串数据库服务器端口号 .net状态服务器端口号

正常的数据库连接字符串配置,这是在MSSQL服务器端口是1433(默认)的情况下。
收藏 0 赞 0 分享

ASP.NET 路径问题的解决方法

相对路径和绝对路径在ASP.NET中可以用~/来解决.
收藏 0 赞 0 分享

asp.net TemplateField模板中的Bind方法和Eval方法

在TemplateField模板中为了能够有限制的或者取出数据库中某列的值时,可以用Bind和Eval方法来实现。以下是Bind方法的格式,Eval的格式也是和Bind一样的。 Bind("列的名称","显示的格式文")
收藏 0 赞 0 分享
查看更多