MVC中为 DropDownListFor 绑定列表项, 一种方案从后台加载列表内容,通过ViewData传递到前台页面.
View:
<div class="editor-label"> @Html.LabelFor(model => model.CategoryType) </div> <div class="editor-field"> @Html.DropDownListFor(model => model.CategoryType, ViewData["Type"] as SelectList) @Html.ValidationMessageFor(model=>model.CategoryType) </div>
Code:
public ActionResult Create() { ViewData["Type"] = GenerateList(); return View(); } public static SelectList GenerateList() { List<SelectListItem> items = new List<SelectListItem>() { new SelectListItem(){Text="Income", Value="income"}, new SelectListItem(){Text="Outcome", Value="outcome"} }; SelectList generateList = new SelectList(items, "Value", "Text"); return generateList; }