InvalidOperationException:不存在具有键 'marka' 的 'IEnumerable<SelectListItem>' 类型的 ViewData 项

InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'marka'

在 MVC 中绑定下拉菜单时,出现此错误:

InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'marka'.

在另一个项目中,此语法完美运行

SO 上有几篇关于此的帖子,但 none 的答案似乎解决了我当前情况下的问题。

型号: Product.cs:

 public class Product
{
    [Key]

    public int Id { get; set; }

    [Required(ErrorMessage = "Proszę podac nazwę produktu")]
    [Display(Name = "Nazwa produktu")]
    [MaxLength(50, ErrorMessage = "Max 50 char")]

    public string Name { get; set; }

    [Display(Name = "Marka produktu")]
    [Required]
    [MaxLength(5, ErrorMessage = "Max 5 char")]

    public string Brand { get; set; }

    [Display(Name = "Cena produktu")]
    [Required]


    public int ProductPrice { get; set; }

    [Display(Name = "Dział")]
    [Required]
    [MaxLength(1, ErrorMessage = "Max 1 char")]

    public string Section { get; set; }

    [Display(Name = "Materiał")]
    [Required]
    [MaxLength(5, ErrorMessage = "Max 5 char")]

    public string Material { get; set; }

    [Display(Name = "Typ")]
    [Required]
    [MaxLength(5, ErrorMessage = "Max 5 char")]

    public string Type { get; set; }
}

Brand.cs:

public class Brand
{
    [Key]
    [Display(Name = "Identyfikator")]
    [MaxLength(5, ErrorMessage = "Max 5 chars")]
    public string Id { get; set; }

    [Display(Name = "Nazwa")]
    [MaxLength(50, ErrorMessage = "Max 50 chars")]
    public string Name { get; set; }
}

查看:

<div class="form-group">
   <label asp-for="Brand" class="control-label"></label>
   <div class="col-md-5">
      @Html.DropDownList("marka", "Select brand")
   </div>
   <span asp-validation-for="Brand" class="text-danger"></span>
</div>

控制器:

// GET: Products/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var product = await _context.Product.FindAsync(id);
        if (product == null)
        {
            return NotFound();
        }

        IEnumerable<SelectListItem> items = _context.Brand.Select(c => new SelectListItem
        {
            Value = c.Id,
            Text = c.Name,
            Selected = c.Id == product.Brand
        }); ;

        if (items != null)
        {
            ViewBag.marka = items;
        }

        return View(product);
    }
 // POST: Products/Edit/5
    // To protect from overposting attacks, enable the specific properties you want to bind to.
    // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Brand,ProductPrice,Section,Material,Type")] Product product)
    {
        if (id != product.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            
            try
            {
                
                string selBra = Request.Form["marka"].ToString();
                product.Brand = selBra;
                _context.Update(product);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(product.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(product);
    }

修复我建议您使用 select 而不是下拉列表的视图,它会自动 select 成为一个项目

 <select class="form-control"  asp-for="brand" asp-items="@ViewBag.marka"></select>

并通过删除 Selected 并添加到 List()

来修复获取操作
var items = _context.Brand.Select(c => new SelectListItem
        {
            Value = c.Id,
            Text = c.Name
          }).ToList(); 

也修复 post 操作,删除绑定,

 public async Task<IActionResult> Edit(int id, Product product)

并从代码中删除

string selBra = Request.Form["marka"].ToString();
product.Brand = selBra;