ArgumentNullException:值不能为空。 (参数'items')

ArgumentNullException: Value cannot be null. (Parameter 'items')

我的代码有问题。我尝试编辑产品的详细信息并添加字段“Category”和“Publisher”作为 DropdownList,同时更新详细信息,如下图所示: here

这是我在控制器中的代码:

[HttpGet]
public IActionResult Edit_Products(string productId)
{
    ViewBag.ListofPublisher = context.Publisher.ToList();
    ViewBag.ListofCategory = context.Category.ToList();

    return View(context.Product.Find(productId));
}

在视图中,我添加了两个下拉列表来加载类别和发布者,并post返回控制器

<div class="form-group">
    <label>Category</label>
    <br />
    <select class="form-control" asp-for="CategoryCode"
            asp-items="@(new SelectList(ViewBag.ListofCategory,"CategoryCode","CategoryName"))">
    </select>
</div>
@*Product Category*@
<div class="form-group">
    <label>Publisher</label>
    <br />
    <select class="form-control" asp-for="PublisherCode"
            asp-items="@(new SelectList(ViewBag.ListofPublisher,"PublisherCode","PublisherName"))">
    </select>
    </div>
    @*Product Publisher*@

在编辑控制器中,我会将其更新为table

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit_Products(Product product,string productCode)
{
    if (ModelState.IsValid)
    {
        Product result = context.Product.SingleOrDefault(p => p.ProductCode.Equals(product.ProductCode));

        try
        {
            string proCode = product.ProductCode;
            result.ProductCode = (product.CategoryCode) + (product.PublisherCode) + (proCode.Substring(proCode.Length - 2));
            result.ProductName = product.ProductName;
            result.Price = product.Price;
            result.Quantity = product.Quantity;
            result.AuthorName = product.AuthorName;
            result.ReleaseYear = product.ReleaseYear;
            result.Ver = product.Ver;
            result.Used = product.Used;
            result.Review = product.Review;
            result.CategoryCode = product.CategoryCode;
            result.PublisherCode = product.PublisherCode;
            result.Picture = product.Picture;

            context.SaveChanges();
        }
        catch (Exception exx)
        {
           ViewBag.Msg = exx.Message;
        }

        return RedirectToAction("Index", "Manage_Products");
    }

    return View();
}

然后我得到这个错误:

ArgumentNullException: Value cannot be null. (Parameter 'items')

请帮助我。

根据我在问题中看到的内容,我假设当您的模型验证失败时,POST 请求会发生错误(即 ModelState.IsValidfalse)。如果是这种情况 - 您需要再次填写 ListofPublisherListofCategory,因为您放入 ViewBag/ViewData 的数据仅在您填充它的请求的生命周期内可用(阅读更多 here)。即调用:

ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();

在您的 POST 方法 return View(); 之前。