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.
Suppose: I have this data:
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
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>
.
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>
.
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);
}
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>