3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
public
static
DataTable dt;
/// <summary>
/// 创建虚拟表
/// </summary>
protected
void
BuildDataTables()
{
dt =
new
DataTable(
"Product"
);
//新建一张商品表,表名为"Product"
dt.Columns.Add(
new
DataColumn(
"ProductID"
));
//商品编号
dt.Columns.Add(
new
DataColumn(
"ProductName"
));
//商品名称
dt.Columns.Add(
new
DataColumn(
"quantity"
));
//购买数量
dt.Columns.Add(
new
DataColumn(
"totalPrice"
));
//商品总价
dt.Columns.Add(
new
DataColumn(
"Price"
));
//商品单价
dt.PrimaryKey =
new
DataColumn[] { dt.Columns[
"ProductID"
] };
//设置主键为ProductID
}
/// <summary>
/// 把虚拟表中的商品编号和购买数量转换成字符串并写入cookie
/// </summary>
protected
void
WriteInCookie()
{
string
str =
""
;
foreach
(DataRow row
in
dt.Rows)
{
str = row[
"ProductID"
] +
"|"
+ row[
"quantity"
] +
","
+ str;
}
str = str.TrimEnd(
','
);
//往购物车中添加商品
HttpCookie aCookie =
null
;
if
(HttpContext.Current.Request.Cookies[
"ShoppingCart"
] ==
null
)
{
//如果Cookies中不存在ShoppingCart,则创建
aCookie =
new
HttpCookie(
"ShoppingCart"
);
}
else
{
//如果Cookies中存在ShoppingCart,则清空
aCookie = HttpContext.Current.Request.Cookies[
"ShoppingCart"
];
aCookie.Value =
null
;
}
aCookie.Value = str;
//设置cookie有效期为1天
aCookie.Expires = DateTime.Now.AddDays(1);
HttpContext.Current.Response.Cookies.Add(aCookie);
}
/// <summary>
/// 从cookie中取出数据填充到虚拟表中
/// </summary>
protected
void
ReadCookie()
{
if
(HttpContext.Current.Request.Cookies[
"ShoppingCart"
] !=
null
)
{
dt =
null
;
BuildDataTables();
//如果Cookies中存在ShoppingCart,则取出数据添加到Datatable中
HttpCookie aCookie = HttpContext.Current.Request.Cookies[
"ShoppingCart"
];
string
cart = aCookie.Value;
string
[] arr = cart.Split(
','
);
for
(
int
i = 0; i < arr.Length; i++)
{
string
[] str = arr[i].Split(
'|'
);
AddDatatable(Convert.ToInt32(str[0]), Convert.ToInt32(str[1]));
}
}
}
/// <summary>
/// 往虚拟表中添加数据
/// </summary>
/// <param name="ProductID">商品编号</param>
/// <param name="Quantity">购买数量</param>
public
void
AddDatatable(
int
ProductID,
int
Quantity)
{
//按照产品编号查询所有产品信息
product prod =
new
ProductInfo().GetProductByProductId(ProductID)[0];
//新建一行数据
DataRow dr = dt.NewRow();
dr[
"ProductID"
] = ProductID;
dr[
"ProductName"
] = prod.productName;
dr[
"quantity"
] = Quantity;
dr[
"Price"
] = prod.price;
dr[
"totalPrice"
] = Quantity * prod.price;
//将这一行数据添加到虚拟表中
dt.Rows.Add(dr);
}
|