Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ArgumentNullException:值不能为null。(参数和项目)_C#_Asp.net_Dropdownlistfor - Fatal编程技术网

C# ArgumentNullException:值不能为null。(参数和项目)

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

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

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

[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
is
false
)。如果是这种情况-您需要再次填写
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();