显示最近查看的项目

时间:2015-12-06 18:46:53

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

我有一个产品表,其中包含许多产品。我在HomeController中有一个Details Action Method,它在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-Shirt,那么我想在新的<div>&#34;最近浏览&#34;中添加该T恤产品。如果他再次访问&#34;观看&#34;然后添加手表产品&#34;最近浏览&#34; <div>

此外,我想根据他最近浏览过的产品展示更多产品。我的意思是,如果他正在访问Xbox,那么Xbox将被添加到最近查看的<div>中,还会有更多与&#34; Gaming&#34;相关的产品。类别将显示在最近查看的<div>下面的新<div>

以下是我尝试的内容,我的想法是将productId存储在Cookie和详细信息视图页面中,获取Cookie请求,获取cookie的productId并找到该产品的类别并显示更多内容该类别的产品。

的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个产品详细信息。不像我看到的那样

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

1 个答案:

答案 0 :(得分:3)

首先,你应该上一些课来保存你最近的产品信息:

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

    public string ProdutName { get; set; }

    public DateTime LastVisited { get; set; }
}

可能在加载时或在登录事件的某个地方填充会话[“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);
    }
}

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

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字典中读取数据并显示最近产品的列表:

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

当然这个代码示例缺少一些空检查和其他东西,但是它应该让你大致了解如何处理这个功能。