Food Ordering System Part 10 | How to Implement a Functional Add to Cart Button


Master the core of E-commerce in Part 10 of our Food Ordering System series! Today, we implement the Add to Cart functionality in ASP.NET Core MVC. We’ll show you how to build the OrderController, handle Cart Sessions, and use Newtonsoft.Json to store food items dynamically. Learn how to check for existing items in the cart, update quantities, and save your cart state using C# Sessions. This is a must-watch tutorial for anyone building a professional Online Food Delivery App with a functional shopping cart!

Step-by-Step Code Explanation

  • Dependency Injection: We inject ApplicationDbContext so the controller can fetch product details (like price and images) from the database when an item is added.

  • The AddToCart Method: This is the heart of the operation. It receives the foodItemId and an optional quantity.

  • Logical Check: The code uses FirstOrDefault to check if the food is already in the user's cart.

    • If it exists: It simply adds to the Quantity (preventing duplicate rows).

    • If it's new: It finds the item in the database and creates a new CartItem object.

  • GetCart() Helper: This method reads the "Cart" from the HttpContext Session. Since sessions store data as strings, it uses JsonConvert.DeserializeObject to turn that string back into a C# List.

  • SaveCart() Helper: This takes your updated list, turns it into a JSON string using JsonConvert.SerializeObject, and saves it back into the user's session.

  • CartItem Model: A simple class that holds the essential data (ID, Name, Price, Quantity, Image) so we don't have to query the database every time the user views their cart.

CONTROLLERS/ORDERCONTROLLER.CS
using FoodOrderingSystem.Models;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;


namespace FoodOrderingSystem.Controllers
{
    public class OrderController : Controller
    {
        private readonly ApplicationDbContext _context;

        public OrderController(ApplicationDbContext context)
        {
            _context = context;
        }

        public IActionResult AddToCart(int foodItemId, int quantity = 1)
        {
            var cart = GetCart();
            var existingItem = cart.FirstOrDefault(c => c.FoodItemId == foodItemId);

            if (existingItem != null)
            {
                existingItem.Quantity += quantity;
            }
            else
            {
                var foodItem = _context.FoodItems.Find(foodItemId);
                cart.Add(new CartItem
                {
                    FoodItemId = foodItemId,
                    Name = foodItem.Name,
                    Price = foodItem.Price,
                    Quantity = quantity,
                    ImageUrl = foodItem.ImageUrl
                });
            }

            SaveCart(cart);
            return RedirectToAction("#");
        }
        private List<CartItem> GetCart()
        {
            var cartJson = HttpContext.Session.GetString("Cart");
            return cartJson == null ? new List<CartItem>() :
                JsonConvert.DeserializeObject<List<CartItem>>(cartJson);
        }

        private void SaveCart(List<CartItem> cart)
        {
            HttpContext.Session.SetString("Cart", JsonConvert.SerializeObject(cart));
        }
    }
    public class CartItem
    {
        public int FoodItemId { get; set; }
        public string Name { get; set; }
        public decimal Price { get; set; }
        public int Quantity { get; set; }
        public string ImageUrl { get; set; }
    }
}

In Part 10, we focus on the bridge between your Menu Page and your Order Controller. This small block of code is the "trigger" that starts the entire shopping process. Without this form, your customers wouldn't be able to select their food!

Step-by-Step Code Explanation

  1. The Form Element (<form>):

    • action="/Order/AddToCart": This tells the browser exactly where to send the data. It points to the OrderController and the AddToCart action we created.

    • method="get": This sends the item ID through the URL (e.g., ?foodItemId=5). This is perfect for simple "Add" actions.

  2. The Hidden Input (<input type="hidden">):

    • This is the "secret messenger." The user doesn't see it on the screen, but it carries the @item.Id (the unique database ID of the Pizza or Burger) to the controller so the system knows exactly which item was clicked.

    • name="foodItemId": This must match the parameter name in your AddToCart method in the Controller.

  3. The Submit Button:

    • type="submit": This is the trigger. When clicked, it packages the hidden ID and fires the request to the server.

    • Bootstrap Classes: btn-primary gives it your brand's blue color, and btn-sm keeps it small and neat inside the food card.

  4. The Icon (<i class="bi bi-cart-plus"></i>):

    • This uses Bootstrap Icons to give a visual cue to the user, making the UI look professional and modern.

Views/Menu/Index.cshtml (Add to Cart Section)
<!-- Add to Cart Form inside the @foreach loop -->
<form action="/Order/AddToCart" method="get" class="d-inline">
    <input type="hidden" name="foodItemId" value="@item.Id" />
    <button type="submit" class="btn btn-primary btn-sm">
        <i class="bi bi-cart-plus"></i> Add
    </button>
</form>

The Add to Cart button. On the Home Page, we keep things simple and fast by using a direct link to trigger the purchase.

Step-by-Step Code Explanation

  1. The Anchor Tag (<a>):

    • Unlike the Menu page which used a form, the Home Page uses a direct URL Link. This is a "Quick Add" feature that makes the user experience faster.

    • href="/Order/AddToCart?foodItemId=@item.Id": This is a Query String. It sends the unique ID of the food item directly to the OrderController. For example, if you click a Burger with ID 5, the link becomes /Order/AddToCart?foodItemId=5.

  2. Razor Syntax (@item.Id):

    • This dynamically inserts the correct ID from your database for every food card automatically. You don't have to write a separate link for every item!

  3. Bootstrap Styling:

    • btn btn-primary: This turns a standard blue link into a professional, clickable button that matches the rest of your site.

  4. The Icon (<i class="bi bi-cart-plus"></i>):

    • We use Bootstrap Icons to add the "plus" sign inside the cart. Icons are essential for high-ranking SEO and professional UX design because they help users understand the button's purpose without reading the text.

Views/Home/Index.cshtml (Quick Add Button)
<!-- Quick Add to Cart Link with Query String -->
<a href="/Order/AddToCart?foodItemId=@item.Id" class="btn btn-primary">
    <i class="bi bi-cart-plus"></i> Add to Cart
</a>

Comments