【问题标题】:Create and Read List<> from cookies从 cookie 创建和读取列表<>
【发布时间】: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


    【解决方案1】:

    最适合您的解决方案是使用 Html5 Web Storage。
    它可以让您在本地浏览器中存储多达 5mb 的空间。
    你只能通过javascript读写。
    示例:

        $('#btnLocalStorage').click(function()  
    {  
        var txtName = $("#txtName").val();  
        //set item  
        localStorage.setItem("EmpName", txtName);  
    });  
    
    $('#btnLocalStorageRemove').click(function()  
     {  
        //remove item  
        localStorage.removeItem("EmpName");  
    });  
    $('#btnLocalStorageClear').click(function()   
     {  
        //clear Local Storage  
        localStorage.clear();  
    });  
    $('#btnLocalStorageLength').click(function()   
     {  
        var localStoragelength = localStorage.length;  
        alert("The length of Local storage is " + localStoragelength);  
    
    });  
    

    顺便说一句,它没有过期时间,你不需要 guid。

    【讨论】:

      【解决方案2】:

      如果你正在使用cookies,那为什么你需要RecentViewed 表呢?在 cookie 中存储最近的产品 ID 对登录用户和匿名用户都有效。

      【讨论】:

      • 请再次阅读问题。现在我将它存储在Session 中,我想将它作为产品列表存储在 Cookies 中,我说 IF 我创建了一个表来存储最近查看的产品,这将是解决方案。
      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 2016-09-08
      • 2016-09-20
      • 2014-01-04
      相关资源
      最近更新 更多