我使用EF代码第一种方法将我的下拉列表与数据库绑定。我的模型类是部门
public class Department
{
[Key]
public int DepartmentID { get; set; }
[Required]
[Display(Name = "Department")]
public string DepartmentName { get; set; }
}
我在ViewData中获取所有部门名称
ViewData["Departments"] = new SelectList(db.Departments,"DepartmentName");
在我看来,我的代码就是这个
@ Html.DropDownList(" Departments","选择部门")
这个代码绑定我的数据但不是名字,但它们是10个对象 MyProjectName.Models.Department
MyProjectName.Models.Department
MyProjectName.Models.Department
MyProjectName.Models.Department
MyProjectName.Models.Department ....
需要帮助我的代码出错。
答案 0 :(得分:3)
尝试使用SelectList
类的correct constructor获取集合,值和文本属性:
ViewData["Departments"] = new SelectList(db.Departments, "DepartmentID", "DepartmentName");
您可能还会考虑使用视图模型并删除弱类型的ViewData。因此,首先定义您的视图模型:
public class MyViewModel
{
public int SelectedDepartmentID { get; set; }
public IEnumerable<SelectListItem> Departments { get; set; }
}
您的控制器操作将填充并传递给视图:
public ActionResult Index()
{
var model = new MyViewModel();
model.Departments = db.Departments.ToList().Select(d => new SelectListItem
{
Value = d.DepartmentID.ToString(),
Text = d.DepartmentName,
});
return View(model);
}
并且在强类型视图中,您可以使用强类型的DropDownListFor版本的帮助程序来生成下拉列表:
@model MyViewModel
...
@Html.DropDownListFor(x => x.SelectedDepartmentID, Model.Departments, "Select Department")