【发布时间】:2016-09-21 15:18:08
【问题描述】:
我正在尝试显示最近查看的产品,到目前为止我已经这样做了。我有一个Product 表,其中存储了许多产品。我有HomeController,它有一个显示产品详细信息的Details() Action 方法。
我写了AddRecentProduct 方法将最近浏览的产品(10)存储在Session
现在我想将这些最近查看的产品列表存储到访问者计算机上的 cookie 中至少 30 天,因为会话已过期。就像最近查看的 Imdb。
另外,如果我在我的数据库RecentlyViewed 中创建另一个表,其中包含rv_id, userId, productId 列,我将如何在其中保存recentViewedList 数据? userId 列将保存已登录用户的 id,但是如果用户是访客(未注册),那么解决方案是什么?那我需要使用 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(List<RecentProduct> list, 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<RecentProduct>;
if (list == null)
{
list = new List<RecentProduct>();
Session["RecentProductList"] = list;
}
AddRecentProduct(list, id.Value, product.Name, 10);
ViewData["RecentProductList"] = list;
return View(product);
}
产品详情查看页面
<div class="col-sm-9">
@{
var recentProductList = ViewData["RecentProductList"] as List<Project.Models.RecentProduct>;
}
@foreach (var recentProduct in recentProductList)
{
<p>@recentProduct.ProdutName (id: @recentProduct.ProductId) </p>
}
</div>
我通过会话获得了想要的结果,现在我想对 cookie 做同样的事情。
这就是我正在尝试的创建 cookie:
List<RecentProduct> yourList = new List<RecentProduct>();
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 View Page 中读取这样的 cookie:
@if (Request.Cookies["YourList"] != null)
{
// Your cookie exists - grab your value and create your List
List<string> yourList = Request.Cookies["YourList"].Value.Split(',').Select(x => Convert.ToString(x)).ToList();
// Use your list here
<p>@yourList</p>
}
我没有得到任何结果。如何读取 cookie 和值?
【问题讨论】:
标签: c# asp.net-mvc asp.net-mvc-4 cookies