🔍 Code Explanation
This method handles the backend logic for switching an item's status without needing a separate "Edit" page.
Authorization (
IsAdmin): This is a critical security gate. It prevents regular users from calling this URL (e.g., via Postman) to disrupt your menu.The Toggle Logic (
!item.IsAvailable): Instead of writing anif/elseblock to check the current state, we use the logical NOT operator (!). This simply flips the current bit in the database. If it wastrue(available), it becomesfalse(unavailable).Entity Framework Tracking: Since
itemwas retrieved via_context.FoodItems.Find(id), Entity Framework is already "tracking" it. Simply changing the property and callingSaveChanges()generates theUPDATESQL command automatically.UX Feedback (
TempData): UsingTempDatais perfect for redirects. It stores the message just long enough to be displayed on the next page load, informing the admin exactly which item was changed and what its new status is.
[HttpPost]
public IActionResult ToggleAvailability(int id)
{
// Security check: Only Admins can toggle availability
if (!IsAdmin()) return RedirectToAction("Index", "Home");
var item = _context.FoodItems.Find(id);
if (item == null) return NotFound();
// Logic to flip the availability status
item.IsAvailable = !item.IsAvailable;
_context.SaveChanges();
// Set notification message for the user
TempData["Success"] = $"{item.Name} is now {(item.IsAvailable ? "available" : "unavailable")}";
return RedirectToAction("ManageMenu");
}
🔍 UI Code Explanation
1. The Razor Ternary Operator
We use the C# ternary operator (condition ? true : false) to make the UI dynamic.
Button Color: If the item is available, we show a Secondary (gray) button to "hide" it. If it’s unavailable, we show a Success (green) button to "activate" it.
Icons: We switch between
bi-eyeandbi-eye-slashusing Bootstrap Icons for a modern look.
2. Hidden Input for Security
Instead of putting the ID in the URL, we use <input type="hidden" name="id" value="@item.Id" />. This ensures that when the button is clicked, the specific Item ID is sent securely within the Request Body to our Controller.
3. Tooltip Engagement
The title attribute changes dynamically. This is great for UX (User Experience) because when an admin hovers over the button, it tells them exactly what will happen (e.g., "Make Unavailable").
<!-- Toggle Availability Form -->
<form asp-action="ToggleAvailability" method="post" class="d-inline"
title="@(item.IsAvailable ? "Make Unavailable" : "Make Available")">
<input type="hidden" name="id" value="@item.Id" />
<button type="submit" class="btn btn-sm @(item.IsAvailable ? "btn-secondary" : "btn-success")">
<i class="bi @(item.IsAvailable ? "bi-eye-slash" : "bi-eye")"></i>
</button>
</form>

Comments
Post a Comment