当我尝试从购物车中删除商品时,为什么会抛出 NullReferenceException?

问题描述 投票:0回答:1

我正在使用 MVC 编写我的第一个 .NET Core Web 应用程序。这是一家商店,所以自然有一个购物车,我可以将商品添加到我的购物车(这些商品在我的代码中称为专辑,因为我将销售音乐专辑)。每当我尝试使用 RemoveFromCart 函数时,都会抛出 NullReferenceException 错误。这是我的职责。

//REMOVE ALBUM FROM CART
public async Task<IActionResult> RemoveFromCart(int id)
{
    var album = await _context.Albums.SingleOrDefaultAsync(a => a.Id == id);
    var cartId = GetCartId();
    var cartItem = await _context.Carts
        .Include(c => c.Albums)
        .SingleOrDefaultAsync(c => c.CartId == cartId);

    if (cartItem == null)
    {
        return NotFound();
    }
    else
    {
        if (cartItem.Albums.Any(a => a.Id == id))
        {
            cartItem.Albums.Remove(album);
            cartItem.Count--;

            // Optionally, remove the entire cart item if count reaches zero
            if (cartItem.Count <= 0)
            {
                _context.Carts.Remove(cartItem);
            }
        }
    }
    await _context.SaveChangesAsync();
    return RedirectToAction("Index");
}

这就是我在购物车编辑视图的 Razor 页面上显示它的方式:

@foreach (var album in Model.Albums)
{
    <tr>
        <td>@album.AlbumName</td>
        <td>
            <form asp-action="RemoveFromCart" asp-controller="Carts" method="post" onsubmit="return confirm('Are you sure you want to remove this album from the cart?');">
                <input type="hidden" name="albumId" value="@album.Id" />
                <button type="submit" class="btn btn-link">Remove</button>
            </form>
        </td>
    </tr>
}

我是 .NET 和 C# 的新手,所以如果我忘记提供任何内容,请告诉我。

我确实知道在迭代所述列表时无法从列表中删除项目,我认为这就是问题所在,但我想不出任何方法来获得我想要的结果。

.net nullreferenceexception
1个回答
0
投票

我不能确定,但我有一些想法。

首先看这里:

cartItem.Albums.Any(a => a.Id == id)

代码已检查

cartItem
是否具有值,但尚未确保
cartItem
具有任何专辑。

第二,看这里:

cartItem.Albums.Remove(album);

此时有可能为空

album

© www.soinside.com 2019 - 2024. All rights reserved.