Food Ordering System Part 25 | Delete Menu Items from Admin Dashboard (Secure C# Logic)


 

📝 Step-by-Step Explanation

Step 1: Authorization Check The code first checks if the user has Administrative privileges using if (!IsAdmin()). This prevents unauthorized users from deleting food items via a direct URL or script.

Step 2: Locating the Item We use _context.FoodItems.Find(id) to search the SQL Server database for the specific item ID. If the item doesn't exist, it returns a NotFound() result to prevent errors.

Step 3: Database Removal Once the item is found, _context.FoodItems.Remove(item) marks the record for deletion, and _context.SaveChanges() permanently deletes the item from the database.

Step 4: User Feedback We use TempData["Success"] to store a message that informs the Admin exactly which item was deleted. This message will appear on the next page after the redirect.

Step 5: Redirection Finally, the user is redirected back to the ManageMenu action so they can see the updated list of food items immediately.


FoodItemController.cs
[HttpPost]
public IActionResult DeleteFoodItem(int id)
{
    if (!IsAdmin()) return RedirectToAction("Index", "Home");

    var item = _context.FoodItems.Find(id);
    if (item == null) return NotFound();

    _context.FoodItems.Remove(item);
    _context.SaveChanges();

    TempData["Success"] = $"{item.Name} has been deleted";
    return RedirectToAction("ManageMenu");
}

📝 Step-by-Step Explanation

Step 1: The Modal Structure The HTML defines a hidden div with the class modal fade. We use bg-danger in the header to visually warn the Admin that this is a destructive action.

Step 2: Dynamic Data Injection Inside the modal body, we have a <strong> tag with the ID deleteItemName. This allows us to inject the specific name of the food item via JavaScript so the Admin knows exactly what they are deleting.

Step 3: The Hidden Form Instead of a simple link, we use a <form> with method="post". This is a security best practice to prevent "One-Click" malicious deletions. The <input type="hidden"> stores the id of the item to be sent to the controller.

Step 4: JavaScript Logic (confirmDelete) The script does three things:

  1. It catches the id and name passed from the "Delete" button.

  2. It assigns those values to the hidden input and the display text in the modal.

  3. It manually triggers the Bootstrap Modal to pop up on the screen.


ManageMenu.cshtml
<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Delete Menu Item</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete <strong id="deleteItemName"></strong>?</p>
                <p class="text-danger"><small>This action cannot be undone!</small></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <form id="deleteForm" method="post" asp-action="DeleteFoodItem">
                    <input type="hidden" name="id" id="deleteItemId" />
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

@section Scripts {
    <script>
        function confirmDelete(id, name) {
            document.getElementById('deleteItemId').value = id;
            document.getElementById('deleteItemName').textContent = name;
            var modal = new bootstrap.Modal(document.getElementById('deleteModal'));
            modal.show();
        }
    </script>
}

📝 Step-by-Step Explanation

Step 1: Button Type and Styling We use type="button" to ensure the button doesn't submit a form prematurely. The classes btn-sm and btn-danger from Bootstrap 5 give it a small, professional red appearance suitable for an admin table.

Step 2: The onclick Event Handler This is the most important part. We call the JavaScript function confirmDelete() that we created earlier. We pass two dynamic parameters using Razor syntax:

  • @item.Id: The unique primary key of the food item.

  • '@item.Name': The name of the item (wrapped in single quotes so it is treated as a string in JS).

Step 3: Visual Icons Inside the button, we use <i class="bi bi-trash"></i>. This refers to Bootstrap Icons, giving the admin a clear visual cue that this button is for deleting/removing an item.

Step 4: Tooltip Accessibility The title="Delete" attribute provides a simple tooltip when a user hovers over the button, improving the user experience (UX) for your Admin Dashboard.


DeleteButton.cshtml
<button type="button" class="btn btn-sm btn-danger" 
        onclick="confirmDelete(@item.Id, '@item.Name')" title="Delete">
    <i class="bi bi-trash"></i>
</button>

Comments