HI
I Use Asp.net core MVC 2 PDF for Learn asp.net core 2
in this book Used Session for store List Of product in the Card. Now i have two codes with the following :
first code :
private List lineCollection = new List();
second :
Public List lineCollection = new List();
when i Used Firs Code (private) all of Things work Correctly ... But I don't know what happened when i Use Second Code (public) List not work correctly .. when i click Button "add product to cart" then one product is added to list correct . but when i want to see List of CartLine in the index of CartController i see two product in the list but i add just one product no two product or when i want to remove that product from list it does not Removed from List ...
the complete Class Cart :
public class Cart
{
private List lineCollection = new List();
public virtual void AddItem(Product product, int quantity)
{
CartLine line = lineCollection
.Where(p => p.Product.ProductID == product.ProductID)
.FirstOrDefault();
if (line == null)
{
lineCollection.Add(new CartLine
{
Product = product,
Quantity = quantity
});
}
else
{
line.Quantity += quantity;
}
}
public virtual void RemoveLine(Product product)
=> lineCollection.RemoveAll(l => l.Product.ProductID == product.ProductID);
public virtual decimal ComputeTotalValue()
=> lineCollection.Sum(e => e.Product.Price * e.Quantity);
public virtual void Clear() => lineCollection.Clear();
public virtual IEnumerable Lines => lineCollection;
}
and the complete Controller Class Cart:
public class CartController : Controller
{
private IProductRepository repository;
private Cart Cart;
public CartController(IProductRepository repo,Cart cart)
{
repository = repo;
Cart = cart;
}
public ViewResult Index(string returnUrl)
{
return View(new CartIndexViewModel
{
Cart = Cart,
ReturnUrl = returnUrl
});
}
public RedirectToActionResult AddToCart(int productId,string returnUrl)
{
Product product = repository.Products.FirstOrDefault(p=>p.ProductID==productId);
if (product!=null)
{
Cart.AddItem(product, 1);
}
return RedirectToAction("Index", new { returnUrl });
}
public RedirectToActionResult RemoveFromCart(int productId,string returnUrl)
{
Product product = repository.Products
.FirstOrDefault(p => p.ProductID == productId);
if (product != null)
{
Cart.RemoveLine(product);
}
return RedirectToAction("Index", new { returnUrl });
}
}
and Session Extension class:
public static class SessionExtensions
{
public static void SetJson(this ISession session,string key,object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T GetJson(this ISession session,string key)
{
var sessiondata = session.GetString(key);
return sessiondata == null ? default(T) : JsonConvert.DeserializeObject(sessiondata);
}
}
...................... ??? Why ??? i dont know what is it happen between private and Public in this piece of code
What I have tried:
i just changed Public to private and all of code work correct i don't know why?