【发布时间】:2011-02-18 15:34:31
【问题描述】:
我正在尝试使用 EF codefirst 在 MVC 3 中开发应用程序。当我使用 int 属性和约定来设置外键关系时,例如
public class Patient
{
public int ConsultantId {get;set;}
}
然后我设置一个创建和编辑页面并使用 HTML.DropDownListFor Helper 生成可能的顾问列表
@Html.DropDownListFor(model => model.ConsultantId, ((IEnumerable<Web.Models.Consultant>)ViewBag.PossibleConsultants).Select(option
=> new SelectListItem
{
Text = Html.DisplayTextFor(_ => option.ConsultantName).ToString(),
Value
= option.ConsultantId.ToString(),
Selected = (Model != null) && (option.ConsultantId
== Model.ConsultantId)
}), "Choose...")
效果很好,但我现在想在患者类上使用 Consultant 对象,例如
public class Patient
{
public virtual Consultant Consultant {get;set;}
}
public class Consultant {
public virtual ICollection<Patient> Patient {get;set;}
}
我现在尝试使用 DropDownListfor 设置视图,但这次是在 model.Consultant 例如
@Html.DropDownListFor(model => model.Consultant, ((IEnumerable<Web.Models.Consultant>)ViewBag.PossibleConsultants).Select(option
=> new SelectListItem
{
Text = Html.DisplayTextFor(_ => option.ConsultantName).ToString(),
Value
= option.ConsultantId.ToString(),
Selected = (Model != null) && (option.ConsultantId
== Model.Consultant.ConsultantId)
}), "Choose...")
创建和编辑页面加载正确,并且在编辑页面上正确选择了顾问,但是当我发布页面时,ModelState 无效,出现此错误“无法转换
'System.String' 输入 'Web.Models.Consultant"。有谁知道如何使用 DropDownListFor 以便可以将模型映射回对象。
【问题讨论】:
标签: c# asp.net-mvc entity-framework