西西软件园多重安全检测下载网站、值得信赖的软件下载站!
软件
软件
文章
搜索

首页编程开发其它知识 → 编程实现cookies浏览历史记录功能

编程实现cookies浏览历史记录功能

前往专题相关软件相关文章发表评论 来源:本站整理时间:2011/1/4 22:34:39字体大小:A-A+

作者:佚名点击:240次评论:0次标签: cookies

cookies清除V4.1.8.8 绿色汉化版
  • 类型:卸载删除大小:1.3M语言:中文 评分:8.3
  • 标签:
立即下载
 1.创建历史记录的实体类
public class LastProducts
{
private int _productid;
private int _categoryid;
private string _imgsrc;
private string _productname;

public LastProducts(int id,int typeid,string imgsrc,string restorename)
{
_productid = id;
_categoryid = typeid;
_imgsrc = imgsrc;
_productname = restorename;
}

public int ProductId
{
get { return _productid; }
}

public int CategoryId
{
get { return _categoryid; }
}

public string ImgSrc
{
get { return _imgsrc; }
}

public string ProductName
{
get { return _productname; }
}
}


2.定义存储cookies的方法
public void HistoryRestore(string cookieName,int objectID)
{
HttpRequest Request = HttpContext.Current.Request;
HttpResponse Response = HttpContext.Current.Response;

if (Request.Cookies[cookieName] != null)
{
HttpCookie tempCurBuyerList = Request.Cookies[cookieName];
string tempstr = tempCurBuyerList.Value;
if (tempstr.IndexOf(",") > 0)
{
string[] sArray = tempstr.Split(',');
bool hasthis = false;

foreach (string s in sArray)
{
if (s == objectID.ToString())
{
hasthis = true;
break;
}
else
{
hasthis = false;
}
}

if (!hasthis) //如果没有ID,则加入
{
if (sArray.Length > 3) //3为存储浏览记录数的数量,实际数量为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(1);
Response.Cookies.Add(tempCurBuyerList);
//或者 Response.Cookies[cookieName].Value = tempstr;
}
else
{
HttpCookie addToCookies = new HttpCookie(cookieName);
addToCookies.Value = objectID.ToString();
addToCookies.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(addToCookies);
}
}


3.读取cookies存储数据
public List<LastProducts> GetLastProducts()
{
HttpRequest Request = HttpContext.Current.Request;

List<LastProducts> list = null;

if (Request.Cookies["restoreid"] != null)
{
HttpCookie tempCurBuyerList = Request.Cookies["restoreid"];

string[] strArr = tempCurBuyerList.Value.Split(',');
list = new List<LastProducts>();

foreach (string s in strArr)
{
ShopProduct model = dal.GetProById(int.Parse(s)); //商品的实体类
if (model != null)
{
list.Add(new Model.Shop.LastProducts(model.ProductID, model.CategoryID, model.ImageHref, model.Name));
}
}
}

return list;
}


4.在用户浏览某产品时记录到cookies中:

HistoryRestore("restoreid",productId);


5.数据源的绑定
  Repeater1.DataSource = GetLastProducts();
Repeater1.DataBind();

    相关评论

    阅读本文后您有什么感想? 已有人给出评价!

    • 8 喜欢喜欢
    • 3 顶
    • 1 难过难过
    • 5 囧
    • 3 围观围观
    • 2 无聊无聊

    热门评论

    最新评论

    发表评论 查看所有评论(0)

    昵称:
    表情: 高兴 可 汗 我不要 害羞 好 下下下 送花 屎 亲亲
    字数: 0/500 (您的评论需要经过审核才能显示)