Asp.net-Mvc
使用 MVC 使用 List<string> 填充 @Html.DropDownList
我正在嘗試使用 MVC 和 Razor 使用列表填充 @Html.DropDownList。貝婁是我的控制器程式碼。所以我需要從我的 ViewBag 中選擇列表並填寫下拉列表。
public ActionResult Register() { sparklingEntities context = new sparklingEntities(); var query = (from discs in context.Disciplines select discs).ToList(); List<string> listOfDiscs = new List<string>(); foreach (var item in query) { listOfDiscs.Add(item.Discipline); } ViewBag.ListOfDisciplines = listOfDiscs; return View(); }謝謝您的幫助。
如果這是在您的模型屬性的編輯器中:
@Html.DropDownList("", new SelectList(ViewBag.ListOfDisciplines, Model))
//Increase performance by Eliminating foreach loop! public ActionResult Register() { sparklingEntities context = new sparklingEntities(); var query = (from discs in context.Disciplines select discs.Discipline); // change this line as discs.Discipline ViewBag.ListOfDisciplines = listOfDiscs; return View(); }