I am creating a shopping cart application. while adding the product in cart, create the cookies as cartId, here the problem occurs is every time i am adding the product, it will create a new cart Id. whats wrong here.
private readonly string _CartItemId;
public ShoppingServices(HttpContextBase httpContext)
: this(httpContext,new PaymentGateway())
{
}
public ShoppingServices( HttpContextBase httpContext,PaymentGateway _paymentGateway)
{
_dbcontext = _paymentGateway;
_CartItemId = GetCartId(httpContext);
}
private string GetCartId(HttpContextBase http)
{
var cookie = http.Request.Cookies.Get("ShoppingCart");
var cartID = String.Empty;
if (cookie == null || string.IsNullOrWhiteSpace(cookie.Value))
{
cookie = new HttpCookie("ShoppingCart");
cartID = Guid.NewGuid().ToString();
cookie.Value = cartID;
cookie.Expires = DateTime.Now.AddDays(5);
http.Response.Cookies.Add(cookie);
}
else
{
cartID = cookie.Value;
}
return cartID;
while adding the product first time, it will create a new cartid and save in cookie ,when reloading and adding another product i am not able to get the cookie. it shows null that what its creating new guid again .
var cookie = http.Request.Cookies.Get("ShoppingCart");
Why it shows null.help me someone?
here i adding the product:
In add product method,cartId= _cartId,which means creating th guid in that and store to cookie.
First request it create a guid and add the product .
Next request i am not able to get the cookie ,so again it create a new cookie.
How to get the cookie ?
public void AddToCart(int productid)
{
var product = _dbcontext.Products.SingleOrDefault(p => p.ProductId == productid);
if (product == null)
{
}
var cartItem = _dbcontext.Carts.SingleOrDefault(c => c.productId == productid && c.CartID == _CartItemId);
if (cartItem != null)
{
cartItem.count++;
}
else
{
cartItem = new Cart
{
productId = productid,
CartID = _CartItemId,
count = 1,
Name = DateTime.Now,
};
_dbcontext.Carts.Add(cartItem);
}
_dbcontext.SaveChanges();
}
}
in the cart table i have cartid and product id , my question if i add the cookie in httpcookie object, it will remain it know,why it shows null.