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
ApplicationDbContextso the controller can fetch product details (like price and images) from the database when an item is added.The
AddToCartMethod: This is the heart of the operation. It receives thefoodItemIdand an optionalquantity.Logical Check: The code uses
FirstOrDefaultto 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
CartItemobject.
GetCart()Helper: This method reads the "Cart" from the HttpContext Session. Since sessions store data as strings, it usesJsonConvert.DeserializeObjectto turn that string back into a C# List.SaveCart()Helper: This takes your updated list, turns it into a JSON string usingJsonConvert.SerializeObject, and saves it back into the user's session.CartItemModel: 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.
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
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.
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 yourAddToCartmethod in the Controller.
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-primarygives it your brand's blue color, andbtn-smkeeps it small and neat inside the food card.
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.
<!-- 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
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 theOrderController. For example, if you click a Burger with ID 5, the link becomes/Order/AddToCart?foodItemId=5.
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!
Bootstrap Styling:
btn btn-primary: This turns a standard blue link into a professional, clickable button that matches the rest of your site.
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.
<!-- 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
Post a Comment