我在应用程序中有一对多的关系。我想使用ViewBag在视图中显示数据,但不是模型中的数据,而是模型类的路径名。我的代码:
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
public ICollection<Instructor> Instructor { get; set; }
}
[Key]
public int InstructorId { get; set; }
public string NameInstructor { get; set; }
public string Email { get; set; }
public string ScienceDegree { get; set; }
public Department Department { get; set; }
控制器类:
[HttpGet]
public ActionResult Create()
{
var item = db.Departments.ToList();
ViewBag.DepartmentName = new SelectList(item, "DepartmentName");
return View();
}
查看课程:
@Html.DropDownList("DepartmentName", new SelectList(ViewBag.DepartmentName, "DepartmentName"))
答案 0 :(得分:1)
您需要将SelectListItem添加到您的SelectList中,而不是实际的部门列表中。您可以遍历列表,将每个项目转换为SelectListItem,然后将其添加到SelectList或使用通用方法。示例(考虑到您的部门列表包含两个名为ID和Name的属性,如果没有,则可以根据需要进行更改):
public static List<System.Web.Mvc.SelectListItem> GenerateSelectList<T>(this IEnumerable<T> itemsToBeAppended)
{
List<SelectListItem> items = new List<SelectListItem>();
foreach (T itemToBeAppended in itemsToBeAppended)
{
SelectListItem item = new SelectListItem();
var type = itemToBeAppended.GetType();
item.Value = type.GetProperty("ID").GetValue(itemToBeAppended).ToString();
item.Text = type.GetProperty("Name").GetValue(itemToBeAppended).ToString();
items.Add(item);
}
return items.OrderBy(x => x.Text).ToList();
}
答案 1 :(得分:0)
请尝试使用DepartmentId代替DepartmentName
@Html.DropDownList("DepartmentId", new SelectList(ViewBag.DepartmentName, "DepartmentName"))