我正在尝试展示最近浏览过的产品,到目前为止我已经做过了.我有一个Product
存储了许多产品的表.我有HomeController
一个Details()
显示产品细节的Action方法.
我写的AddRecentProduct
方法存储了最近浏览过的产品(10)Session
现在我想将这些最近查看的产品列表存储到访问者计算机上至少30天的cookie中,因为会话到期了.就像最近观看的Imdb一样.
另外如果我在数据库中RecentlyViewed
使用列创建另一个表,我rv_id, userId, productId
将如何在此保存recentViewedList数据?userId列将保存loggedIn用户的id但是如果用户是Guest(未注册)那么解决方案是什么呢?我需要使用GUID吗?
RecentProduct.cs
public class RecentProduct { public int ProductId { get; set; } public string ProdutName { get; set; } public string ImageUrl { get; set; } public DateTime LastVisited { get; set; } }
调节器
public void AddRecentProduct(Listlist, int id, string name, int maxItems) { var item = recentProductList.FirstOrDefault(t => t.ProductId == id); if (item == null) { list.Add(new RecentProduct { ProductId = id, ProdutName = name, LastVisited = DateTime.Now, }); } while (list.Count > maxItems) { list.RemoveAt(0); } } public ActionResult Details(int? id) { if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest); Product product = db.Products.Find(id); if (product == null) return HttpNotFound(); var list = Session["RecentProductList"] as List ; if (list == null) { list = new List (); Session["RecentProductList"] = list; } AddRecentProduct(list, id.Value, product.Name, 10); ViewData["RecentProductList"] = list; return View(product); }
ProductDetails查看页面
@{ var recentProductList = ViewData["RecentProductList"] as List; } @foreach (var recentProduct in recentProductList) { @recentProduct.ProdutName (id: @recentProduct.ProductId)
}
我正在通过会话获得所需的结果,现在我想用cookie做同样的事情.
这就是我正在尝试创建cookie:
ListyourList = new List (); RecentProduct rc = new RecentProduct(); rc.ProdutName = product.Name; rc.ProductId = product.ProductId; rc.ImageUrl = product.ImagePath; rc.LastVisited = DateTime.Now; yourList.Add(rc); var yourListString = String.Join(",", yourList); // Create a cookie HttpCookie yourListCookie = new HttpCookie("YourList", yourListString); // The cookie will exist for 7 days yourListCookie.Expires = DateTime.Now.AddDays(7); // Write the Cookie to your Response Response.Cookies.Add(yourListCookie);
和在ProductDetails查看页面读取这样的cookie:
@if (Request.Cookies["YourList"] != null) { // Your cookie exists - grab your value and create your List ListyourList = Request.Cookies["YourList"].Value.Split(',').Select(x => Convert.ToString(x)).ToList(); // Use your list here @yourList
}
我没有得到任何结果.我怎样才能读取cookie和值?