Kgenov17 / Model-me-this-Football

0 stars 0 forks source link

Shopping Cart #2

Open Kgenov17 opened 1 year ago

Kgenov17 commented 1 year ago

Проект

Kgenov17 commented 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 items;

    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 };
    }
}
  1. Връзка с html

<!Doctype html>

@model List

Shopping Cart

@foreach (var item in Model) { }
Product 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")