1. 首先定义存储cookies的对象:
public class ResortCookiesData { private string _Img; private string _resortName; private int _id; public ResortCookiesData(string img, string resortname, int id) { _Img = img; _resortName = resortname; _id = id; } public string Img { get { return _Img; } } public string ResortName { get { return _resortName; } } public int Id { get { return _id; } } }
2. 读取cookies存储数据并绑定到数据控件中:
protected void bindCookies() { if (Page.Request.Cookies["resortid"] != null) { HttpCookie _tempCurBuyerList = Page.Request.Cookies["resortid"]; string[] strArr = _tempCurBuyerList.Value.Split(','); ArrayList list = new ArrayList(); foreach (string s in strArr) { SendNet.Model.Product m = pm.Product.GetModel(int.Parse(s)); if (m != null) { list.Add(new ResortCookiesData(m.Img, m.ProductName, m.ProductId)); } } rpthistory.DataSource = list; rpthistory.DataBind(); } }
3. 定义存储cookies的方法:
protected void History_Resorts(string _cookiesName, int objectID) { if (Page.Request.Cookies[_cookiesName] != null) { HttpCookie _tempCurBuyerList = Page.Request.Cookies[_cookiesName]; string _tempstr = _tempCurBuyerList.Value; if (_tempstr.IndexOf(",") > 0) { string[] sArray = _tempstr.Split(','); bool hasthis = false; foreach (string i in sArray) { if (i == objectID.ToString()) { hasthis = true; break; } else { hasthis = false; } } if (!hasthis)//如果没有ID,则加入 { if (sArray.Length > 6)//6为存储浏览记录数的数量,实际数量为7 {//超过限定,去掉最先入队的元素 _tempstr = _tempstr.Substring(0, _tempstr.LastIndexOf(",")); } //队列 _tempstr = objectID.ToString() + "," + _tempstr; } } else { //_tempstr += "," + objectID.ToString(); if (_tempstr != objectID.ToString()) { _tempstr = objectID.ToString() + "," + _tempstr; } } _tempCurBuyerList.Value = _tempstr; _tempCurBuyerList.Expires = DateTime.Now.AddDays(7); Page.Response.Cookies.Add(_tempCurBuyerList); } else { HttpCookie _addToCookies = new HttpCookie(_cookiesName); _addToCookies.Value = objectID.ToString(); _addToCookies.Expires = DateTime.Now.AddDays(7); Page.Response.Cookies.Add(_addToCookies); } }
4. 在用户浏览某产品时记录到cookies中:
History_Resorts("resortid", m.ProductId);
(此功能到此完成)