我已经使用列表/编辑/删除功能完成了这个EF MVC应用程序(代码优先)。一切正常,但现在我需要添加两个下拉字段。产品具有需要编辑的类别和子类别。这就是我到目前为止所做的:
ProductSubcategoryID是外键的主类
public class Product
{
public int ProductID { get; set; }
public string Name { get; set; }
public string ProductNumber { get; set; }
public int? ProductSubcategoryID { get; set; }
public IEnumerable<SelectList> SelectedCat = new List<SelectList> {};
public IEnumerable<SelectList> SelectedSubCat = new List<SelectList> {};
}
public class ProductCategory
{
public int ProductCategoryID { get; set; }
public string Name { get; set; }
}
public class ProductSubcategory
{
public int ProductSubcategoryID { get; set; }
public int ProductCategoryID { get; set; }
public string Name { get; set; }
}
在Product controller类中,我有:
public ActionResult Create()
{
ViewBag.SubcatSelection = new SelectList(dbSubcat.ProductSubcategories, "ProductSubcategoryID", "Name"); ;
return View();
}
并点击编辑:
@Html.LabelFor(model => model.ProductSubcategoryID)
@Html.DropDownListFor(model => model.SelectedSubCat, ViewBag.SubcatSelection as SelectList, "ProductSubcategoryID", "Name");
结果:
没有类型&#39; IEnumerable&lt; SelectListItem&gt;&#39;有钥匙&#39; SelectedSubCat&#39;。