显示最近查看的项目 [英] Display recently viewed items

查看:54
本文介绍了显示最近查看的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品表,其中有很多产品.我的HomeController中有一个Details Action方法,该方法在Details View页面中返回产品详细信息.

I have a Product table which has many products in it. I have a Details Action Method in my HomeController which returns the product details in Details View Page.

假设:我有此数据:

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>中.如果他再次访问手表",则将手表产品添加到最近浏览"中<div>.

Now, I want is that If some user visits T-Shirt then I want to add that T-shirt product in a new <div> of "Recently Viewed". If he again visits "Watch" then add watch product in "Recently Viewed" <div>.

我也想根据他最近浏览的产品展示更多产品.我的意思是,如果他正在访问Xbox,则Xbox将被添加到最近查看的<div>中,并且与游戏"类别相关的更多产品也将在最近查看的<div>下面的新<div>中显示.

Also I want to show more products based on his recently viewed products. I mean if he's visiting Xbox then Xbox will be added in recently viewed <div> and also more products related to "Gaming" category will be shown in a new <div> below the recently viewed <div>.

这是我正在尝试的方法,我的想法是将productId存储在cookie中和详细信息视图"页面中,获取cookie请求,获取来自cookie的productId,并找到该产品的类别,并从中显示更多产品该类别.

Here is what I'm trying, my idea is to just store the productId in the cookies and in the Details View Page, get Cookie Request, get the productId fro cookie and find the category of that product and show more products from that category.

HomeController

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);
    }

我在详细信息查看页面"中写了这个.它向我显示最近查看产品"的ID和详细信息,但Cookie中只有1个产品的详细信息.不如我所见

I wrote this in my Details View Page. It is showing me Recently View product's Id and details, but only 1 product's detail from cookies. not as my as i view

<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>

推荐答案

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

First you should make some class to hold your recent product information:

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

    public string ProdutName { get; set; }

    public DateTime LastVisited { get; set; }
}

也许是在加载时或在登录事件中的某处,使用用户保留的最新产品列表填充Session ["RecentProductList"].

Maybe on load or somewhere on login event fill Session["RecentProductList"] with user's persisted recent list of products.

然后您将具有此功能,可根据提供的信息存储最近的产品:

Then you have this function that stores recent product based on supplied information:

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);
    }
}

然后,您可以最小化控制器的代码以获取详细信息:

Then you can minimize your controller's code for Details:

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);
}

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

Then in your view read data from ViewData dictionary and display list of recent products:

<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>

当然,此代码示例缺少一些null检查和其他内容,但应该为您提供有关如何实现此功能的一般思路.

Of course this code sample lacks some null checking and other stuff, but it should give you general idea on how to approach this functionality.

这篇关于显示最近查看的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆