为注册用户实现复杂的数据类型配置--购物车

web.config配置

<connectionStrings>
  <add name="NorthwindConnectionString" connectionString="Data Source=b764e28a5fe449f/helen;Initial Catalog=Northwind;Integrated Security=True"
            providerName="System.Data.SqlClient" />
 </connectionStrings>

 

<profile>
   <properties>
    <add name="ShoppingCart" type="ShoppingCart" serializeAs="Binary"/>
   </properties>
  </profile>
  <authorization>
   <deny users="?"/>
  </authorization>
  <authentication mode="Forms">
   <forms loginUrl ="Login.aspx"></forms>
  </authentication>

 

 

ShoppingCart.cs类

using System;
using System.Collections;

[Serializable]
public class ShoppingCart
{
    public Hashtable _CartItems = new Hashtable();
    // 创建属性CartItems,用于获取购物车中所有商品
    public ICollection CartItems
    {
        get { return _CartItems.Values; }
    }

    // 创建属性Total,用于获取购物车中商品总价
    public decimal Total
    {
        get
        {
            decimal sum = 0;
            foreach (CartItem item in _CartItems.Values)
            {
                sum += item.Price * item.Quantity;
            }
            return sum;
        }
    }
    // 实现将商品添加到购物车中
    public void AddItem(int ID, string Name, decimal Price)
    {
        CartItem item = (CartItem)_CartItems[ID];
        if (item == null)
        {
            _CartItems.Add(ID, new CartItem(ID, Name, Price));
        }
        else
        {
            item.Quantity++;
            _CartItems[ID] = item;
        }
    }
    // 从购物车中删除商品
    public void RemoveItem(int ID)
    {
        CartItem item = (CartItem)_CartItems[ID];
        if (item == null)
        {
            return;
        }
        item.Quantity--;
        if (item.Quantity == 0)
        {
            _CartItems.Remove(ID);
        }
        else
        {
            _CartItems[ID] = item;
        }
    }
}

//实现表示商品的业务实体类
[Serializable]
public class CartItem
{
    private int _ID;
    private string _Name;
    private decimal _Price;
    private int _Quantity = 1;
    // 创建属性ID
    public int ID
    {
        get { return _ID; }
    }
    // 创建属性Name
    public string Name
    {
        get { return _Name; }
    }
    // 创建属性Price
    public decimal Price
    {
        get { return _Price; }
    }
    // 创建属性Quantity
    public int Quantity
    {
        get { return _Quantity; }
        set { _Quantity = value; }
    }
    // 创建类构造函数
    public CartItem(int ID, string Name, decimal Price)
    {
        _ID = ID;
        _Name = Name;
        _Price = Price;
    }
}

 

 

 

default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>为注册用户实现复杂数据类型的个性化用户配置</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <fieldset style="width: 620px">
                <legend class="mainTitle">实现验证用户个性化用户配置</legend>
                <table border="0" cellpadding="5" width="620px">
                    <tr align="center">
                        <td>
                            <p class="littleTitle">
                                待售商品列表</p>
                        </td>
                        <td>
                            <p class="littleTitle">
                                购物车</p>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                                SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice] FROM [Products]"></asp:SqlDataSource>
                            <asp:GridView ID="ProductGrid" runat="server" OnSelectedIndexChanged="AddCartItem"
                                Width="300px" AllowPaging="True" AutoGenerateColumns="False" BackColor="White"
                                BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ProductID"
                                DataSourceID="SqlDataSource1" Font-Size="Small" PageSize="5">
                                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                                <RowStyle BackColor="White" ForeColor="#330099" />
                                <Columns>
                                    <asp:CommandField ButtonType="Image" SelectImageUrl="~/Images/button_buy.gif" ShowSelectButton="True" />
                                    <asp:BoundField DataField="ProductName" HeaderText="商品名称" SortExpression="ProductName" />
                                    <asp:BoundField DataField="UnitPrice" DataFormatString="{0:c}" HeaderText="单价" SortExpression="UnitPrice" />
                                </Columns>
                                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                            </asp:GridView>
                        </td>
                        <td valign="top">
                            <asp:GridView ID="CartGrid" AutoGenerateColumns="False" DataKeyNames="ID" OnSelectedIndexChanged="RemoveCartItem"
                                CellPadding="4" Width="320px" runat="Server" BackColor="White" BorderColor="#CC9966"
                                BorderStyle="None" BorderWidth="1px" Font-Size="Small">
                                <Columns>
                                    <asp:ButtonField CommandName="select" Text="Remove" ButtonType="Image" ImageUrl="~/Images/button_del.gif" />
                                    <asp:BoundField DataField="Name" HeaderText="商品名称" />
                                    <asp:BoundField DataField="Price" HeaderText="单价" DataFormatString="{0:c}" />
                                    <asp:BoundField DataField="Quantity" HeaderText="数量" />
                                </Columns>
                                <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                                <RowStyle BackColor="White" ForeColor="#330099" />
                                <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
                                <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                                <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                            </asp:GridView>
                            <asp:Label ID="lblTotal" runat="Server" CssClass="littleTitle" /></td>
                    </tr>
                </table>
            </fieldset>
        </div>
    </form>
</body>
</html>

 

.cs

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;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindShoppingCart();
        }
    }

    // 显示Profile对象中保存的购物车信息
    protected void BindShoppingCart()
    {
        //如果Profile中存储的购物车的商品不为空,则进行数据绑定并计算总价
        if (Profile.ShoppingCart != null)
        {
            CartGrid.DataSource = Profile.ShoppingCart.CartItems;
            CartGrid.DataBind();
            lblTotal.Text = "总价:" + Profile.ShoppingCart.Total.ToString("c");
        }
    }

    // 将选中商品添加到购物车中
    protected void AddCartItem(object sender, EventArgs e)
    {
        // 获取被选中数据行
        GridViewRow row = ProductGrid.SelectedRow;
        // 获取主键ID的值
        int ID = (int)ProductGrid.SelectedDataKey.Value;
        // 获取商品名称
        String Name = row.Cells[1].Text;
        // 获取商品单价
        decimal Price = Decimal.Parse(row.Cells[2].Text, System.Globalization.NumberStyles.Currency);
        // 如果Profile中存储的购物车对象为null,则创建一个相应对象
        if (Profile.ShoppingCart == null)
        {
            Profile.ShoppingCart = new ShoppingCart();
        }
        // 利用前面获取的数据,在Profile对象购物车中添加被选中的商品
        Profile.ShoppingCart.AddItem(ID, Name, Price);
        // 显示购物车数据
        BindShoppingCart();
    }
    // 将选中商品从购物车中删除
    protected void RemoveCartItem(object sender, EventArgs e)
    {
        // 获取被选中商品的主键ID
        int ID = (int)CartGrid.SelectedDataKey.Value;
        // 利用ID,从Profile对象购物车中删除该商品
        Profile.ShoppingCart.RemoveItem(ID);
        // 显示购物车数据
        BindShoppingCart();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
特别说明请注意: 根许多网友反应, using Maticsoft.Functions; 这些代码看不懂 其实Functions 这个dll是我定义常用的函数类,如果需要跟我联系索取http://sql8.net 下面有我的群号, 其中 ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); 这是我的商品信息的类,三层结构,这个在用时你们只能换成你们自己的,这些代码完全可以删除, 比如 MyDr[1] = _p.Title; 用来读取商品名的,你们可以改MyDr[1] = dr["productname"].ToString();就行了, AddToCart.aspx页面代码 无标题页 <asp:TextBox ID="TextBox1" runat="server" Text='' Width="44px"> <asp:Label ID="Label1" runat="server" Text=''> 保存 取消 编辑 继续购物 清空购物 下订单 AddToCart.aspx.cs页面代码 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; using Maticsoft.Functions;public partial class AddToCart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int ProID; HttpCookie cookie; bool Tempbl = false; string Tempstr; if (!Page.IsPostBack) { if (!object.Equals(Request.QueryString["id"], null)) { ProID = int.Parse(Request.QueryString["id"]); //创购物cookie yxy .//sql8.net if (object.Equals(Request.Cookies["ztbscart"], null)) cookie = new HttpCookie("ztbscart"); else cookie = Request.Cookies["ztbscart"]; //判断是否已存在于购物内 yxy // sql8.net for (int i = 0; i < cookie.Values.Keys.Count; i++) { if (!object.Equals(cookie.Values.Keys[i], null)) { Tempstr = cookie.Values.AllKeys[i].ToString(); if (Tempstr.Trim() != "") { if (ProID == int.Parse(cookie.Values.AllKeys[i])) { Tempbl = true; break; } } } } //不未购买过则加入购物 yxy //sql8.net if (!Tempbl) cookie.Values.Add(ProID.ToString(), "1"); else { } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); } BindGrid(); } } //绑定数据 yxy //sql8.net private void BindGrid() { DataTable MyDt; DataRow MyDr; string str = ""; MyDt = new DataTable(); MyDt.Columns.Add(new DataColumn("id", str.GetType())); MyDt.Columns.Add(new DataColumn("Title", str.GetType())); MyDt.Columns.Add(new DataColumn("Num", str.GetType())); MyDt.Columns.Add(new DataColumn("Price", str.GetType())); MyDt.Columns.Add(new DataColumn("Discount", str.GetType())); MyDt.Columns.Add(new DataColumn("Vipprice", str.GetType())); MyDt.Columns.Add(new DataColumn("Totle", str.GetType())); if (!object.Equals(Request.Cookies["ztbscart"], null)) { HttpCookie cookie = Request.Cookies["ztbscart"]; double Totle; //Response.Write("|" + Request.Cookies["ztbscart"].Values.Keys[1].ToString() + "|"); //Response.End(); for (int i = 0; i < cookie.Values.Keys.Count; i++) { int id; MyDr = MyDt.NewRow(); if (cookie.Values.AllKeys[i] != "" && cookie.Values[i] != "") { id = int.Parse(cookie.Values.AllKeys[i].ToString()); ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); MyDr[0] = id; MyDr[1] = _p.Title; MyDr[2] = cookie.Values[i]; MyDr[3] = _p.Price; MyDr[4] = _p.Discount; MyDr[5] = _p.Vipprice1; Totle = double.Parse(MyDr[2].ToString()) * double.Parse(MyDr[5].ToString()); MyDr[6] = Totle; MyDt.Rows.Add(MyDr); } } GridView1.DataSource = MyDt.DefaultView; GridView1.DataBind(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //编辑某行数量 yxy //sql8.net GridView1.EditIndex = e.NewEditIndex; BindGrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //取消更新 yxy //sql8.net GridView1.EditIndex = -1; BindGrid(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //更新数量 yxy //sql8.net string num; TextBox tempbx = new TextBox(); Label templb = new Label(); tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6]).Controls[1]; num = tempbx.Text.ToString(); HttpCookie cookie = new HttpCookie("ztbscart"); for (int i = 0; i < GridView1.Rows.Count; i++) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); if (e.RowIndex == i) tempnum = num; else { templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); } if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } //Response.End(); TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); GridView1.EditIndex = -1; Message.GoTo("AddToCart.aspx"); } protected void LinkButton4_Click(object sender, EventArgs e) { //继续购物 yxy //sql8.net Message.WebClose(); } protected void LinkButton3_Click(object sender, EventArgs e) { //清空购物 yxy //sql8.net CheckBox tempcb = new CheckBox(); HttpCookie cookie = new HttpCookie("ztbscart"); Label templb = new Label(); for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; if (!tempcb.Checked) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); Message.GoTo("AddToCart.aspx"); } protected void CheckAll_CheckedChanged(object sender, EventArgs e) { //全选事件 yxy //sql8.net CheckBox tempcb = new CheckBox(); bool tempbl; tempcb = (CheckBox)(GridView1.HeaderRow.Cells[0]).Controls[1]; tempbl = tempcb.Checked; for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; tempcb.Checked = tempbl; } } } _________________________________________________________________________ 如转载请注明原出处 www.sql8.net

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值