【问题标题】:InvalidOperationException: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'marka'InvalidOperationException:没有具有键“marka”的“IEnumerable<SelectListItem>”类型的 ViewData 项
【发布时间】:2022-01-25 14:11:49
【问题描述】:

在 MVC 中绑定下拉菜单时,我收到此错误:

InvalidOperationException:没有 ViewData 类型的项 具有键 'marka' 的 'IEnumerable'。

在另一个项目中,这种语法完美地工作

在 SO 上有几篇关于此的帖子,但没有一个答案似乎可以解决我当前情况下的问题。

型号: 产品.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; }
}

品牌.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);
    }

【问题讨论】:

    标签: c# asp.net-core .net-core entity-framework-core asp.net-core-mvc


    【解决方案1】:

    修复视图我建议你使用选择而不是下拉列表,它会自动选择一个项目

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

    并通过删除 Selected 并添加到 List() 来修复 get 操作

    var items = _context.Brand.Select(c => new SelectListItem
            {
                Value = c.Id,
                Text = c.Name
              }).ToList(); 
    

    也修复 post 动作,移除 Bind,

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

    并从代码中删除

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

    【讨论】:

    • 谢谢,它有帮助。但正如我上面提到的,我的代码在另一个模型有点不同的项目中工作,为什么这次不是?
    • 不客气!只需使用最新的模板。下拉列表已有 10 年历史。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-26
    • 2020-06-28
    • 2020-08-20
    • 2011-02-20
    • 2015-03-11
    相关资源
    最近更新 更多