ShoppingCartController.cs
private readonly ILogger _logger;
private readonly DBContext _dbContext;
private const string CartSessionKey = "CartId";
private string ShoppingCartId { get; set;}
public ShoppingCartController(ILogger logger, DBContext dBContext)
{
_logger = logger;
_dbContext = dBContext;
}
public async void AddToCart(int id)
{
ShoppingCartId = GetCartID();
// Bottom line code breaks with the InvalidOperationException
Cart cart = await _dbContext.Carts.FirstOrDefaultAsync(c => c.CartId == ShoppingCartId && c.ProductId == id);
if (cart == null)
{
// If cart is null then we create a new cart
Cart newCart = new Cart
{
ProductId = id,
CartId = ShoppingCartId,
Product = await _dbContext.Products.FirstOrDefaultAsync(p => p.ProductId == id),
Count = 1,
CreatedDate = DateTime.Now,
};
await _dbContext.Carts.AddAsync(newCart);
}
else
{
cart.Count++;
}
await _dbContext.SaveChangesAsync();
}
private string GetCartID()
{
if(HttpContext.Session.Keys.Contains(CartSessionKey) == false)
{
if (!string.IsNullOrWhiteSpace(HttpContext.User.Identity.Name))
{
HttpContext.Session.SetString(CartSessionKey,HttpContext.User.Identity.Name);
}
else
{
Guid tempCartId = Guid.NewGuid();
HttpContext.Session.SetString(CartSessionKey, tempCartId.ToString());
}
}
return HttpContext.Session.GetString(CartSessionKey);
}
}
Dashboard.cshtml
@foreach(var prod in @ViewBag.Products)
{
@prod.ProductName
More Details
// This is where it would add the product to cart
Add to cart
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... stem-priva