IEnumerable <selectlistitem>没有绑定到枚举

时间:2015-11-22 14:21:12

标签: c# asp.net asp.net-mvc razor enums

我正在尝试使用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>

1 个答案:

答案 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)

http://www.drdobbs.com/windows/aspnet-mvc-51/240168353