gpt4 book ai didi

c# - 没有具有键 'IEnumerable' 的 "key"类型的 ViewData 项

转载 作者:行者123 更新时间:2023-11-30 13:45:39 24 4
gpt4 key购买 nike

我的代码是这样的

 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; }
}
}

Controller

  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" })

方式2:

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();
}

在 View 中:

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

关于c# - 没有具有键 'IEnumerable<SelectListItem>' 的 "key"类型的 ViewData 项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27916642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com