我正在尝试使用enum
作为DropDownList
的文字和值的来源。不幸的是它没有按预期工作 - 已经填充了DropDownList但没有选择任何选项
这是枚举:
public enum OrderLineState
{
Draft = 0,
InProcess = 1,
Done = 2
}
以下是我如何从枚举中填充DropDown:
public IEnumerable<Helper.OrderLineStateData> GetOrderLineStates()
{
return from Enums.OrderLineState s in Enum.GetValues(typeof(Enums.OrderLineState))
select new Helper.OrderLineStateData() { OrderLineStateId = (int)s, OrderLineStateName = s.ToString() };
}
这是控制器:
[Authorize]
public async Task<ActionResult> EditOrderLine(int id)
{
ViewBag.OrderLineStates = new SelectList(_olr.GetOrderLineStates(), "OrderLineStateId", "OrderLineStateName");
var result = await _olr.GetAllOrderLines(id);
return PartialView(result);
}
最后 - Razor View:
<td>
@Html.DropDownListFor(x => item.LineState, (IEnumerable<SelectListItem>)ViewBag.OrderLineStates, new { @class = "form-control" })
</td>
答案 0 :(得分:1)
如果您是MVC 5,则有一个枚举助手。试试这个:
public enum OrderLineState
{
[Display(Name = "Draft")]
Draft = 0,
[Display(Name = "In Process")]
InProcess = 1,
[Display(Name = "Done")]
Done = 2
}
然后
@Html.EnumDropDownListFor(model => model.LineState)