【问题标题】:ArgumentNullException: Value cannot be null. Parameter name: items selectlist .net coreArgumentNullException:值不能为空。参数名称:items selectlist .net core
【发布时间】:2019-09-12 17:28:49
【问题描述】:

Selectlist 非常适合 Get 请求。但是对于 Post 请求,它给出了 null 异常

控制器代码:

var category = _context.CategoryTbl.ToList();
List<SelectListItem> li = new List<SelectListItem>();
li.Add(new SelectListItem { Text = "Select Category", Value = "0" });
foreach (var m in category)
{
     li.Add(new SelectListItem { Text = m.Name, Value = m.Id.ToString() });
     ViewBag.category =li;
}

查看代码:

@Html.DropDownListFor(model => model.Category, new SelectList(ViewBag.category, "Value", "Text"), new { @id = "ddlCategory", style = "width: 200px;", @class = "form-control input-lg" })

我收到以下错误:

ArgumentNullException:值不能为空。参数名称:items

【问题讨论】:

  • 能否请您发布整个异常堆栈?不仅仅是错误消息。

标签: c# asp.net-core


【解决方案1】:

三件事:

  1. 将选项作为属性存储在视图模型上更为合适。这消除了像这样的动态问题。当您保持强类型时,跟踪问题会容易得多。

  2. 您无需创建SelectList。所需要的只是您已经拥有的IEnumerable&lt;SelectListItem&gt;

  3. 这里最好使用SelectTagHelper

综合起来,在你的模型上添加:

public IEnumerable<SelectListItem> CategoryOptions { get; set; }

那么在你看来:

<select asp-for="Category" asp-items="@Model.CategoryOptions"></select>

【讨论】:

    【解决方案2】:

    它与您的 POST 操作有关,如果您返回相同的视图,您还需要一个 ViewBag.category

    您可以在返回视图之前使用get方法中的方式对其进行初始化,也可以直接使用new SelectList(_context.CategoryTbl, "Id", "Name"),参考以下代码:

    [HttpPost]  
    public async Task<IActionResult> MyPostMethodName(Model model)
        {
            if (!ModelState.IsValid)
            {
    
            }
            //your post logic
            //...
            //need a  ViewBag.category if you return the same view,
            ViewBag.category = new SelectList(_context.CategoryTbl, "Id", "Name", model.Category);
    
            return View(product);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-29
      • 2019-11-26
      • 2019-03-19
      • 2015-07-25
      • 1970-01-01
      • 2015-07-17
      • 1970-01-01
      相关资源
      最近更新 更多