/// <summary>
/// 删除Cookie
/// </summary>
/// <param name="skuID">从购物车选择要删除的商品ID</param>
/// <returns>先从Cookie里提取出所有的商品并放进一个字典 Dictionary<int, int> dit = new Dictionary<int, int>();里</returns>
/// 从字典里删除传过来的商品,再重新拼接字符串放到Cookie里,
/// 并把从Cookie拼接好的字符串返回到一个声明的集合(List<ShoppingGoods>)里
public static List<ShoppingGoods> DeletCookie(int skuID)
{
if (skuID != 0)
{
//先从Cookie里提取出所有的商品并放进一个字典(Dictionary<int, int>)里
HttpCookie cookie = HttpContext.Current.Request.Cookies["MyShoppingCart"];//声明Cookie容器
if (cookie != null)//如果Cookie里面有值
{
Dictionary<int, int> dit = new Dictionary<int, int>();//声明字典
string goodsID = cookie.Value;//解析Cookie值并赋值给变量GoodsID
goodsID = goodsID.Substring(0, goodsID.Length - 1);//检索GoodsID字符串的长度
string[] gdsArray = goodsID.Split(‘,‘);//检索GoodsID字符串的长度后拆解
int Count = 0;//声明Int数量
foreach (var v in gdsArray)//迭代拆解出来的字符串数组
{
if (v == "" || v == null)//判断字符串Value == null || == “”
{
continue;
}
else//如果不为Null或“”
{
string[] strValue = v.Split(‘-‘);//拆解字符串
string key = strValue[0];//给拆解后的字符串strValue[0]赋值给 string 变量 Key
int strKey = 0;//声明int变量
bool parseOKstrKey = int.TryParse(key, out strKey);//转换 string 变量 key字符串为 Int key
string value = strValue[1];//给字符串的strValue[1]赋值给 string 变量 value
int strCount = 0;//声明int变量
bool parseOKstrCount = int.TryParse(value, out strCount);//转换string value字符串为 Int value
if (dit.ContainsKey(strKey))//判断字典
{
dit[strKey] += strCount;
Count = gdsArray.Count();//数量统计
}
else
{
dit.Add(strKey, strCount);
Count = gdsArray.Count() + 1;
}
}
}
#region 从字典里删除传过来的商品,再重新拼接字符串放到Cookie里
if (dit.ContainsKey(skuID))
{
dit.Remove(skuID);//删除商品
string strCookie = null;//声明拼接剩下的字符串名
ShoppingMallContext db = new ShoppingMallContext();//数据上下文
List<ShoppingGoods> lsg = new List<ShoppingGoods>();//New一个 ShoppingGoods 的集合
foreach (var vdit in dit)//迭代字典里剩余的字符串
{
strCookie += vdit.Key + "-" + vdit.Value + ",";//给字符串strCookie赋值
ShoppingGoods sg = new ShoppingGoods();//New类
sg.GoodsName = db.GoodsSKUs// 很据传过来的vdit.Key查商品名(GoodsName)
.Where(f => f.GoodsID == skuID)
.Select(f => f.Goods.GoodsName)
.ToString();
sg.Goodssku = db.GoodsSKUs //根据传过来的vdit.Key查Goodssku
.Where(f => f.GoodsID == skuID)
.Single();
sg.Count = strCookie[1];//根据传过来的vdit.Value给ShoppingGoods 属性Count 赋值
lsg.Add(sg);
}
//并把从Cookie拼接好的字符串返回到一个声明的List<ShoppingGoods>里
var cookies = new HttpCookie(strCookie);
cookies.Expires = DateTime.Today.AddDays(1);//设置Cookie的过期时间
cookies.Value = strCookie;//Cookie的值
HttpContext.Current.Request.Cookies.Add(cookies);//添加到Cookie
return lsg;
}
else
{
return null;
}
#endregion//从字典里删除传过来的商品,再重新拼接字符串放到Cookie里
}
else
{
return null;
}
}
else
{
return TiQuCookies();
}
}