use*_*667 5 c# cookies asp.net-mvc asp.net-mvc-4
我正在尝试展示最近浏览过的产品,到目前为止我已经做过了.我有一个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; }
}
Run Code Online (Sandbox Code Playgroud)
调节器
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);
}
Run Code Online (Sandbox Code Playgroud)
ProductDetails查看页面
<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>
Run Code Online (Sandbox Code Playgroud)
我正在通过会话获得所需的结果,现在我想用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);
Run Code Online (Sandbox Code Playgroud)
和在ProductDetails查看页面读取这样的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>
}
Run Code Online (Sandbox Code Playgroud)
我没有得到任何结果.我怎样才能读取cookie和值?
| 归档时间: |
|
| 查看次数: |
1410 次 |
| 最近记录: |