c# - 显示最近查看的项目

标签 c# asp.net asp.net-mvc asp.net-mvc-4 cookies

我有一个产品表,其中包含许多产品。我的 HomeController 中有一个详细信息操作方法,它返回详细信息 View 页面中的产品详细信息。

假设:我有以下数据:

ProductID | ProductName | Price | CategoryId
    1     |  T-Shirt    |  120  |  Clothing
    2     |   Shirt     |  150  |  Clothing
    3     |   Watch     |  220  |  Watches
    4     |  Laptop     |  820  |  Computing
    5     | Samsung S6  |  520  |  Mobile
    6     |    Xbox     |  320  |  Gaming

现在,我想要的是,如果某个用户访问 T 恤,那么我想将该 T 恤产品添加到新的 <div> 中“最近查看”。如果他再次访问“ watch ”,则在“最近查看”中添加 watch 产品<div> .

此外,我想根据他最近查看的产品展示更多产品。我的意思是,如果他正在访问 Xbox,那么 Xbox 将被添加到最近查看的 <div> 中。更多与“游戏”类别相关的产品将显示在新的<div>中下面最近查看过<div> .

这就是我正在尝试的,我的想法是将productId存储在cookie中和详细信息 View 页面中,获取Cookie请求,从cookie中获取productId并找到该产品的类别并显示更多产品该类别。

家庭 Controller

public ActionResult Details(int? id)
    {
        if (id == null)
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        Product product = db.Products.Find(id);
        if (product == null)
            return HttpNotFound();

        //Creating cookies
        HttpCookie _userActivity = new HttpCookie("UserActivity");
        _userActivity["ProductID"] = id.ToString();
        _userActivity["ProdutName"] = product.Name;
        _userActivity["Lastvisited"] = DateTime.Now.ToShortTimeString();

        //Adding Expire Time of cookies
        _userActivity.Expires = DateTime.Now.AddDays(5);

        //Adding cookies to current web response
        Response.Cookies.Add(_userActivity);

        //Reading cookies
        HttpCookie readcookie = Request.Cookies["UserActivity"];
        string productID , productName, lastVisited ;
        if (readcookie != null)
        {
            productID = readcookie["ProductID"];
            productName = readcookie["ProdutName"];
            lastVisited = readcookie["Lastvisited"];
        }

        return View(product);
    }

我在详细信息 View 页面中写了此内容。它向我显示最近查看产品的 ID 和详细信息,但只有 1 个来自 cookie 的产品详细信息。不像我想象的那样

<div class="row">
        <div class="col-sm-9">
            @{
                var product = Request.Cookies["UserActivity"].Values;
            }
            <p>@product</p>

            <br />
            <h2>@Html.DisplayFor(model => model.Name)</h2>
 </div>

最佳答案

首先,您应该创建一些类来保存您最近的产品信息:

public class RecentProduct
{
    public int ProductId { get; set; }

    public string ProdutName { get; set; }

    public DateTime LastVisited { get; set; }
}

也许在加载时或登录事件的某个位置用用户持久保存的最近产品列表填充 Session["RecentProductList"]。

然后您就可以使用此功能根据提供的信息存储最近的产品:

public void AddRecentProduct(List<RecentProduct> list, int id, string name, int maxItems)
{
    // list is current list of RecentProduct objects
    // Check if item already exists
    var item = list.FirstOrDefault(t => t.ProductId == id);
    // TODO: here if item is found, you could do some more coding
    //       to move item to the end of the list, since this is the
    //       last product referenced.
    if (item == null)
    {
        // Add item only if it does not exist
        list.Add(new RecentProduct
        {
            ProductId = id,
            ProdutName = name,
            LastVisited = DateTime.Now,
        });
    }

    // Check that recent product list does not exceed maxItems
    // (items at the top of the list are removed on FIFO basis;
    // first in, first out).
    while (list.Count > maxItems)
    {
        list.RemoveAt(0);
    }
}

然后您可以最小化 Controller 的代码以获取详细信息:

public ActionResult Details(int? id)
{
    if (id == null)
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    Product product = db.Products.Find(id);
    if (product == null)
        return HttpNotFound();

    // Read list of recent products from session
    var list = Session["RecentProductList"] as List<RecentProduct>;
    if (list == null)
    {
        // If list not found in session, create list and store it in a session
        list = new List<RecentProduct>();
        Session["RecentProductList"] = list;
    }

    // Add product to recent list (make list contain max 10 items; change if you like)
    AddRecentProduct(list, id.Value, product.Name, 10);

    // Store recentProductList to ViewData keyed as "RecentProductList" to use it in a view
    ViewData["RecentProductList"] = list;
    return View(product);
}

然后在您的 View 中从 ViewData 字典中读取数据并显示最近产品的列表:

<div class="row">
    <div class="col-sm-9">
        @{
            var recentProductList = ViewData["RecentProductList"] as List<RecentProduct>;
        }
        @* Do whatever you like with recentProductList here (e.g. display its data) *@
        @foreach (var recentProduct in recentProductList)
        {
            <p>@recentProduct.ProdutName (id: @recentProduct.ProductId)</p>
        }

        <br />
        <h2>@Html.DisplayFor(model => model.Name)</h2>
    </div>
</div>

当然,此代码示例缺少一些空检查和其他内容,但它应该让您了解如何实现此功能。

关于c# - 显示最近查看的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34121235/

相关文章:

html 选择下拉滚动条 - 仅当存在下拉框时

c# - 编译 HelloWorld.cs 问题

c# - 使变量成为类的实例

c# - 批量插入到自引用表中

c# - 从错误中记录多少信息?

asp.net-mvc - 将文件附加/上传到尚未保存的注释 - 对此的最佳策略是什么?

c# - 正则表达式系统的 IndexOutOfRangeException

c# - ASP.NET MVC : How do I change where Ajax. BeginForm 将在页面加载后发布到?

asp.net - 命名 Dom 元素的 id 属性的最佳实践

c# - 如何将 System.Web.Cache 传递到我的服务层