没有具有键 "key" 的类型 'IEnumerable<SelectListItem>' 的 ViewData 项

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

我的代码是这样的

 namespace DiagnosisApp.Models
{
    public class ProcedurePrice
    {
        public int ID { get; set; }


        public int DepartmentID { get; set; }
        public int ProcedureID { get; set; }
        public int InsuranceProviderID { get; set; }
        public int ProcedureCategoryID { get; set; }
        public int ProcedureSubCategoryID { get; set; }



        [ForeignKey("ID")]
        public virtual Department Department { get; set; }

        [ForeignKey("ID")]
        public virtual InsuranceProvider InsuranceProvider { get; set; }

        [ForeignKey("ID")]
        public virtual ProcedureCategory ProcedureCategory { get; set; }
        [ForeignKey("ID")]
        public virtual ProcedureSubCategory ProcedureSubCategory { get; set; }
    }
}

控制器

  public ActionResult Create()
        {
            ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
            ViewBag.ProcedureSubCategoryID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
            return View();
        }

在我看来

 @Html.DropDownList("ProcedureID", null, new { @class = "form-control" })
  @Html.ValidationMessageFor(model => model.ProcedureID)

我觉得一切正常,但它会引发错误

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'ProcedureID'.

谁能指出我做错了什么?

错误是你在传递 ProcedureID int Html.DropDownList() 时把它放在 ViewBag.ProcedureSubCategoryID 中,并且你还传递了 SelectList 参数 null。一个快速的解决方法是将 Html.DropDownList() 中的 ProcedureSubCategoryID 替换为 ProcedureID 作为第一个参数中的键:

你有三种方法可以解决这个问题。

方式一:

而不是在第二个接受类型 SelectList 的参数中传递 null 你可以这样做:

@Html.DropDownList("ProcedureID", ViewBag.ProcedureSubCategoryID as SelectList, new  { @class="form-data" })

方式二:

public ActionResult Create()
{
  ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
  ViewBag.ProcedureSubCategoryID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
  return View();
}


@Html.DropDownList("ProcedureSubCategoryID", null, new { @class = "form-control" })

方式三:

或者替代方法是在您的操作中将其存储在 ProcedureID 中:

public ActionResult Create()
{
       ViewBag.DepartmentID = new SelectList(db.Departments, "ID", "Name");
       ViewBag.ProcedureID = new SelectList(db.ProcedureSubCategories, "ID", "Name");
       return View();
}

在视图中:

@Html.DropDownList("ProcedureID", null, new { @class = "form-control" })

我想你漏掉了

ViewBag.ProcedureID = new SelectList(db.ProcedureCategory, "ID", "Name");

我认为你必须初始化 ViewBag.ProcedureId