【发布时间】:2012-09-21 09:31:43
【问题描述】:
我正在使用 MVC4 和 EF Code First,但在获取 DropDownList 以更新模型类型的外键时遇到问题。
这是我的模型:
public class Customer
{
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Party
{
public int PartyID { get; set; }
public virtual Customer Host { get; set; }
public string Location { get; set; }
public DateTime Date { get; set; }
}
所以一个派对有一个Host 这是一个Customer
在 /Party/Create GET 方法的控制器中,我在 ViewBag 中传递了一个客户列表:
ViewBag.Customers = new SelectList(db.Customers, "CustomerID", "FirstName");
然后在视图中我将其渲染为 DropDownList:
@Html.DropDownListFor(model => model.Host, ViewBag.Customers as SelectList, String.Empty)
这一切都很好,我可以从下拉列表中的客户列表中进行选择。但是,当我提交表单时,/Party/Create POST 方法不会插入数据,因为ModelState 无效。查看ModelState,我可以看到所选客户的CustomerID 存在,但它无法从字符串转换为Customer 类型的对象
我错过了什么?
【问题讨论】:
标签: asp.net-mvc entity-framework ef-code-first