MVC 5 Code First脚手架,关系简单
我正在做一些实验性编程以赶上ASP MVC。
我为包含房间的建筑物创建了一个项目。 一个非常简单的一对多关系。 我试图让脚手架工作,并从旧的MVC示例看起来这应该工作。 但是,Rooms中的BuildingId字段未映射到建筑模型 – 视图中没有选择列表。
我的模特是:
namespace BuildingManagement.Models { public class Building { public int Id { get; set; } [Required] public string Name { get; set; } public string Address { get; set; } public string Street { get; set; } public string City { get; set; } public string Province { get; set; } public string PostalCode { get; set; } [Display(Name = "Phone")] [DataType(DataType.PhoneNumber)] [Required] public string PhoneMain { get; set; } [Display(Name = "Contact")] [Required] public string ContactName { get; set; } public string Description { get; set; } public virtual ICollection Rooms { get; set; } } }
和
namespace BuildingManagement.Models { public class Room { public int Id { get; set; } [Required] public string Name { get; set; } public string Type { get; set; } public int BuildingId { get; set; } } }
我使用Entity Framework生成了带有视图的控制器,它创建了表单,但没有在Room编辑视图中创建预期的Building选择列表。 它显示整数输入字段。
我错过了什么?
你应该改变这个:
public class Room { public int Id { get; set; } [Required] public string Name { get; set; } public string Type { get; set; } public int BuildingId { get; set; } }
至
public class Room { public int Id { get; set; } [Required] public string Name { get; set; } public string Type { get; set; } [ForeignKey("ContainingBuilding")] public int BuildingId { get; set; } public virtual Building ContainingBuilding{ get; set;} }
这样,脚手架将为建筑物生成选择列表。
public List CountryListItems {get; set;} public int CountryId {get; set;}
上面的样本模型
Model.CountryListItems= new List(); CountryListItems.Add(new SelectListItem { Text = "Albania", Value = "1" }); CountryListItems.Add(new SelectListItem { Text = "Bangladesh", Value = "2", Selected = true }); CountryListItems.Add(new SelectListItem { Text = "Canada", Value = "3" });
上面的示例代码可以在控制器或其他生成器模型类中使用。
@Html.DropDownListFor(model => model.CountryId, model.CountryListItems, "-- Select Status --")
上面的示例视图块。