In Part 21, we are implementing a vital business rule: Order Cancellation. This backend logic ensures that while users have the flexibility to change their minds, they can't cancel an order that is already being prepared or out for delivery.
Step-by-Step Code Explanation
[HttpPost]Attribute: This ensures the method only responds to POST requests (usually from a button click or form submission), which is a security best practice for data-changing operations.Identity Verification: We fetch the
UserIdfrom the session. If the user isn't logged in, they are redirected to the Login page.Ownership Check:
_context.Orders.FirstOrDefault(o => o.Id == orderId && o.UserId == userId)ensures the order actually exists and—more importantly—belongs to the person trying to cancel it.Business Logic Validation:
This is the "Safety Lock." The code checks if the status is anything other than "Pending" or "Confirmed."
If the kitchen has already started "Preparing" the food, we stop the cancellation and use
TempData["Error"]to send a warning message back to the user.
Status Update & Persistence: If the order passes the check, we set
order.Statusto "Cancelled" and call_context.SaveChanges()to commit that change to the database.User Feedback: We store a success message in
TempDataand redirect the user back to their order list to see the updated status.
[HttpPost]
public IActionResult CancelMyOrder(int orderId)
{
var userId = HttpContext.Session.GetInt32("UserId");
if (userId == null) return RedirectToAction("Login", "Account");
var order = _context.Orders.FirstOrDefault(o => o.Id == orderId && o.UserId == userId);
if (order == null) return NotFound();
// Only allow cancellation if status is Pending or Confirmed
if (order.Status != "Pending" && order.Status != "Confirmed")
{
TempData["Error"] = "Order cannot be cancelled at this stage!";
return RedirectToAction("TrackOrder", new { id = orderId });
}
order.Status = "Cancelled";
_context.SaveChanges();
TempData["Success"] = "Order cancelled successfully!";
return RedirectToAction("MyOrders");
}
In the final step of Part 21, we are adding the Cancel Order button to our frontend. This snippet is designed to be "smart"—it only appears when the order status allows it, ensuring your users have a clean and error-free experience in both the My Orders list and the Track Order dashboard.
Step-by-Step Code Explanation
Conditional Rendering (
@if): This is the most important part of the UI logic. By checkingorder.Status == "Pending" || order.Status == "Confirmed", the button automatically disappears once the restaurant starts preparing the food. This prevents users from trying to cancel an order that is already in the kitchen.POST Form Submission: We wrap the button in a
<form>withmethod="post". This is a security requirement because cancelling an order changes data on the server, and GET requests should never be used for such actions.JavaScript Confirmation: The
onsubmit="return confirm(...)"attribute adds a simple but effective native browser popup. It asks, "Are you sure?" before the form sends, preventing accidental cancellations.Hidden Input: Since the user doesn't need to type their Order ID, we use
<input type="hidden">to silently pass the@order.Idto ourCancelMyOrdercontroller action.Styling:
btn-outline-danger: Uses a red outline style to signal a "destructive" or "warning" action.w-100: Ensures the button stretches to fill its container, making it easy to tap on mobile devices.bi-x-circle: Adds a clear "X" icon to represent cancellation visually.
@if (order.Status == "Pending" || order.Status == "Confirmed")
{
<form asp-action="CancelMyOrder" method="post" onsubmit="return confirm('Are you sure you want to cancel this order?');">
<input type="hidden" name="orderId" value="@order.Id" />
<button type="submit" class="btn btn-outline-danger w-100">
<i class="bi bi-x-circle"></i> Cancel Order
</button>
</form>
}

Comments
Post a Comment