我想为打开我的网站的用户提供一个ID,并将一些项目添加到他们的购物车中,即使他们没有注册该服务。只需添加,然后在他们想要结账时继续注册。如果他们在添加内容后没有去结账,那么关闭他们的浏览器,2天后回来,我想从数据库中检索他们以前的订单。
如何提供用户唯一的ID并在下次访问时记住它?
我认为我需要使用cookies,但不知道究竟是怎么回事?
答案 0 :(得分:0)
当用户向购物车添加内容时,请按以下方式运行javascript:
var storedId = localStorage.getItem('myId');
if(storedId == null)
{
storedId = parseInt(Math.Random * 1000); // or better, use UUID generation from here: https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
localStorage.setItem('myId', storedId); // for future reference
}
现在,无论何时向购物车添加内容,都要发布ID,例如
控制器:
[HttpPost]
public ActionResult AddToCard(string userId, string productId, int quantity)
{
/// perform your saving to db
}
Ajax(或您使用的任何框架):
$.post('/somewhere', {userId: storedId, productId: 'whatever', quantity: 1});
答案 1 :(得分:0)
我使用cookie和数据库做了类似的事情。所以在c#中你可以有一个Basket表,并且在该表中有一个UserId列和一个ProductId列。然后,从您的控制器中,您将拉出UserId所在的用户篮子数据库中的用户篮子。
设置cookie:
string cookieValue = Guid.NewGuid().ToString();
//Creating a cookie which has the name "UserId"
HttpCookie userIdCookie = new HttpCookie("userId");
userIdCookie.Value = cookieValue;
//This is where you would state how long you would want the cookie on the client. In your instance 2 days later.
userIdCookie.Expires = DateTime.Now.AddDays(3);
Response.SetCookie(userIdCookie);
然后在控制器中获取cookie:
public ActionResult Basket()
{
//Getting the cookie which has the name "userId" and assigning that to a variable.
string userId = Request.Cookies.Get("userId").Value;
var basket = _context.Basket.Where(x => x.UserId == userId);
return View(basket);
}
注意:我在这里使用了Request.Cookies.Get(“userId”),因为如果使用Response.Cookies.Get(“userId”),则cookie“UserId”不存在,然后它会为你创建cookie。