没有类型为’IEnumerable ‘的ViewData项具有键“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' that has the key 'ProcedureID'.
谁能指出我在这里做错了什么?
错误的是,当您传递ProcedureID
int Html.DropDownList()
时,您将它放在ViewBag.ProcedureSubCategoryID
,并且您正在传递SelectList
参数null
。 快速解决方法是将Html.DropDownList()
ProcedureID
替换为ProcedureID
作为第一个参数中的键:
你有三种方法来解决这个问题。
方式1:
而不是在接受类型SelectList
第二个参数中传递null
,您可以执行以下操作:
@Html.DropDownList("ProcedureID", ViewBag.ProcedureSubCategoryID as SelectList, new { @class="form-data" })
Way2:
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" })
方式3:
或替代方法是将其存储在您的操作中的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进行初始化
你用的是部分??
如果你使用partial,那很简单,你可以找到错误的解决方案这个错误说你没有查看数据类型SelectListItem键是’ProcedureId’我认为你使用Partial进行创建并在你的索引页面上调用它所以你应该将此代码传递给索引操作结果,就像我的代码一样:
public ActionResult Index() { ViewData["ProcedureID"] = new SelectList(db.Procedures, "ProcedureId", "ProcedureName"); return View(); } public ActionResult Create() { return View(); }