You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在点击按钮时删除ASP.NET MVC中特定的列表元素?

Solution to Implement Basket Item Deletion

Alright, let's tackle that delete functionality for your shopping basket rows. Here's a step-by-step solution tailored to your existing ASP.NET MVC code:

1. Add a Unique Identifier to Your Basket Class

First, we need a way to uniquely target each basket item for deletion. Update your Basket class to include an Id property:

public class Basket
{
    public int Id { get; set; }
    public int Quantity { get; set; }
    public float Price { get; set; }
    public string Name { get; set; }
    public double Total { get; set; }

    public Basket(int quantity, float price, string name, double total)
    {
        Quantity = quantity;
        Price = price;
        Name = name;
        Total = total;
        // Generate a simple unique ID (use Guid.NewGuid() for stricter uniqueness if needed)
        Id = HomeController.basketItems.Count + 1;
    }
}

2. Add a Delete Action to the BasketController

Next, create an action method in BasketController that handles removing the specified item from the basket:

public class BasketController : Controller
{
    // GET: Basket
    public ActionResult Basket()
    {
        var itemList = HomeController.basketItems;
        return View(itemList);
    }

    // POST: Basket/Delete
    [HttpPost]
    public ActionResult Delete(int id)
    {
        // Locate the item to delete using its unique ID
        var itemToRemove = HomeController.basketItems.FirstOrDefault(basket => basket.Id == id);
        
        if (itemToRemove != null)
        {
            HomeController.basketItems.Remove(itemToRemove);
        }

        // Redirect back to the Basket view to show the updated list
        return RedirectToAction("Basket");
    }
}

3. Update the View to Trigger the Delete Action

Modify your basket view to wrap each Delete button in a form that posts to the Delete action, passing the item's ID:

<tbody class="customBody">
@foreach (var item in Model) {
<tr class="customRow">
    <td class="customData">@item.Name</td>
    <td class="customData">@item.Quantity</td>
    <td class="customData">@item.Price</td>
    <td class="customData">@item.Total</td>
    <td class="customData">
        @using (Html.BeginForm("Delete", "Basket", FormMethod.Post))
        {
            @Html.Hidden("id", item.Id)
            <button type="submit" class="btn-dark">Delete</button>
        }
    </td>
</tr>
}
</tbody>

4. (Optional) Add Ajax for No-Refresh Deletion

For a smoother user experience without page reloads, use jQuery to handle the delete asynchronously:

Update the Delete Button in the View

<td class="customData">
    <button class="btn-dark delete-btn" data-id="@item.Id">Delete</button>
</td>

Add jQuery Script to Handle the Click

Place this script at the bottom of your Basket view (ensure jQuery is loaded in your layout first):

<script>
$(document).ready(function() {
    $('.delete-btn').click(function(e) {
        e.preventDefault();
        var itemId = $(this).data('id');
        
        if (confirm('Are you sure you want to remove this item from your basket?')) {
            $.post('/Basket/Delete', { id: itemId }, function() {
                // Fade out and remove the row after successful deletion
                $(this).closest('tr').fadeOut(300, function() {
                    $(this).remove();
                });
            }.bind(this));
        }
    });
});
</script>

Important Note for Multi-User Scenarios

Right now, your basketItems is a static list—this means all users will share the same basket, which isn't suitable for production. Replace the static list with user-specific storage like Session:

// In HomeController, replace the static list with Session
private List<Basket> GetUserBasket()
{
    if (Session["UserBasket"] == null)
    {
        Session["UserBasket"] = new List<Basket>();
    }
    return (List<Basket>)Session["UserBasket"];
}

// Update your Add to Cart action
[HttpPost]
public ActionResult Yacht1(int yachtQuantity, float yachtPrice, string yachtName)
{
    double totalPrice = Convert.ToDouble(yachtQuantity) * Convert.ToDouble(yachtPrice);
    Basket basketItem = new Basket(yachtQuantity, yachtPrice, yachtName, totalPrice);
    var userBasket = GetUserBasket();
    userBasket.Add(basketItem);
    Session["UserBasket"] = userBasket;
    
    return RedirectToAction("Yacht1");
}

// Update BasketController to use Session
public ActionResult Basket()
{
    var userBasket = (List<Basket>)Session["UserBasket"] ?? new List<Basket>();
    return View(userBasket);
}

[HttpPost]
public ActionResult Delete(int id)
{
    var userBasket = (List<Basket>)Session["UserBasket"] ?? new List<Basket>();
    var itemToRemove = userBasket.FirstOrDefault(b => b.Id == id);
    
    if (itemToRemove != null)
    {
        userBasket.Remove(itemToRemove);
        Session["UserBasket"] = userBasket;
    }
    
    return RedirectToAction("Basket");
}

内容的提问来源于stack exchange,提问作者SeventhWarhawk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 09:37:51