[英]How to retrieve data from 2 columns combined in database and display in drop down list?
[英]How change display data in drop down list with name of model class to real data which saved in database?
我在應用程序中有一對多的關系。 我想使用 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"))
您需要將 SelectListItem 添加到您的 SelectList 而不是實際的部門列表。 您可以迭代您的列表,將每個項目轉換為 SelectListItem,然后您可以將其添加到您的 SelectList 或使用通用方法。 示例(考慮到您的部門列表包含兩個名為 ID 和名稱的屬性,如果沒有,您可以根據需要更改它們):
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();
}
請嘗試 DepartmentId 而不是 DepartmentName
@Html.DropDownList("DepartmentId", new SelectList(ViewBag.DepartmentName, "DepartmentName"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.