|
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);
}
作者:Crazy Ma
|