我的代码就像这样
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'.
有谁可以指出我在这里做错了什么?
答案 0 :(得分:7)
错误的是,当您传递ViewBag.ProcedureSubCategoryID
int ProcedureID
时,您将它放在Html.DropDownList()
中,并且您正在传递SelectList
参数null
。快速解决方法是将ProcedureSubCategoryID
替换为ProcedureID
Html.DropDownList()
作为第一个参数中的关键字:
你有三种解决方法。
您可以执行以下操作,而不是在接受类型null
的第二个参数中传递SelectList
:
@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" })
答案 1 :(得分:1)
我想你错过了像
这样的东西ViewBag.ProcedureID = new SelectList(db.ProcedureCategory, "ID", "Name");
我认为你必须对ViewBag.ProcedureId进行初始化
答案 2 :(得分:0)
你正在使用partial ??
如果你使用partial,那非常简单,你可以找到错误的解决方案 此错误表示您没有查看数据类型为SelectListItem,该键为'ProcedureId' 我认为您使用Partial进行创建并在索引页面上调用它 因此,您应该将此代码传递给索引操作结果,就像我的代码一样:
public ActionResult Index()
{
ViewData["ProcedureID"] = new SelectList(db.Procedures, "ProcedureId", "ProcedureName");
return View();
}
public ActionResult Create()
{
return View();
}