Open Kgenov17 opened 1 year ago
1.Създадох 3 класа в models :
// class Product
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
// class CartItem
public class CartItem { public Product Product { get; set; } public int Quantity { get; set; } }
//class ShoppingCart
public class ShoppingCart
{
private List
public ShoppingCart()
{
items = new List<CartItem>();
}
public void AddItem(Product product, int quantity)
{
var existingItem = items.FirstOrDefault(item => item.Product.Id == product.Id);
if (existingItem != null)
{
existingItem.Quantity += quantity;
}
else
{
var newItem = new CartItem { Product = product, Quantity = quantity };
items.Add(newItem);
}
}
public void RemoveItem(int productId)
{
var itemToRemove = items.FirstOrDefault(item => item.Product.Id == productId);
if (itemToRemove != null)
{
items.Remove(itemToRemove);
}
}
public void ClearCart()
{
items.Clear();
}
public List<CartItem> GetItems()
{
return items;
}
}
2.След това генерирах Контролер:
public class CartController :Controller { private ShoppingCart cart;
public CartController()
{
cart = new ShoppingCart();
}
public ActionResult AddToCart(int productId, int quantity)
{
var product = GetProductFromDatabase(productId);
cart.AddItem(product, quantity);
return RedirectToAction("Index");
}
public ActionResult RemoveFromCart(int productId)
{
cart.RemoveItem(productId);
return RedirectToAction("Index");
}
public ActionResult ClearCart()
{
cart.ClearCart();
return RedirectToAction("Index");
}
public ActionResult Index()
{
var items = cart.GetItems();
return View(items);
}
private Product GetProductFromDatabase(int productId)
{
return new Product { Id = productId, Name = "Sample Product", Price = 9.99m };
}
}
<!Doctype html>
@model ListProduct | Quantity | Price | Total | |
---|---|---|---|---|
@item.Product.Name | @item.Quantity | @item.Product.Price | @(item.Product.Price * item.Quantity) | @Html.ActionLink("Remove", "RemoveFromCart", new { productId = item.Product.Id }) |
@Html.ActionLink("Clear Cart", "ClearCart")
Проект