C# ArgumentNullException:值不能为null。(参数和项目)
我的代码有问题。我尝试编辑产品的详细信息,并添加一个字段“Category”和“Publisher”作为下拉列表,同时更新详细信息,如下图所示: 这是我在控制器中的代码:C# ArgumentNullException:值不能为null。(参数和项目),c#,asp.net,dropdownlistfor,C#,Asp.net,Dropdownlistfor,我的代码有问题。我尝试编辑产品的详细信息,并添加一个字段“Category”和“Publisher”作为下拉列表,同时更新详细信息,如下图所示: 这是我在控制器中的代码: [HttpGet] public IActionResult Edit_Products(string productId) { ViewBag.ListofPublisher = context.Publisher.ToList(); ViewBag.ListofCategory = context.Cat
[HttpGet]
public IActionResult Edit_Products(string productId)
{
ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();
return View(context.Product.Find(productId));
}
在视图中,我向loads Category和Publisher添加了两个dropdownList,并将其发回controller
<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*@
然后我得到了这个错误:
ArgumentNullException:值不能为null。(参数“items”)
请帮助我。根据我在问题中看到的情况,我假设当您的模型验证失败时,POST请求会发生错误(即
ModelState.IsValid
isfalse
)。如果是这种情况-您需要再次填写ListofPublisher
和ListofCategory
,因为您放入ViewBag/ViewData的数据仅在您填充它的请求的生命周期内可用(请阅读更多)。i、 e.电话:
ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();
在
返回视图()之前代码>在您的POST方法中。代码中的哪一行抛出错误?这是否回答了您的问题?错误代码在两行中报告,从我能告诉的信息中选择…asp items=“@(新的SelectList(ViewBag.ListofCategory,“CategoryCode”,“CategoryName”)”>
…或者发布者列表行返回一个null
值。嗯……错误似乎很清楚……一个或两个列表是null
。如果列表正在初始化,则必须有其他内容使一个或两个列表为空。您是否跟踪过这一点,比如在代码上设置断点并检查列表以查看它们是否为null
?这将是故障排除101。
ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();