具有Enum的DropDown - Select的Value属性

时间:2014-12-26 06:20:10

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

我正在关注来自DropDown的{​​{1}}。

Enum

html的输出就像这个@Html.DropDownListFor(model => model.Month1, Enum.GetNames(typeof(Models.InputMonths)).Select(e => new SelectListItem { Text = e }), "--Select Month--", new { @class = "form-control", @id = "Month1" }) public enum InputMonths { January = 1, February = 2, March = 3, April = 4, May = 5, June = 6, July = 7, August = 8, September = 9, October = 10, November = 11, December = 12 }

我希望<option>January</option>中的valuenumeric像这样<option value="1">January</option>

value属性如何附带数值?

1 个答案:

答案 0 :(得分:1)

您必须在Value

中指定new SelectListItem { Text = e, Value = enumValue }

修改

List<InputMonths> months = Enum.GetValues(typeof(InputMonths)).Cast<InputMonths>().ToList();
@Html.DropDownListFor(model => model.Month1, months.Select(e => new SelectListItem { Text = e, Value = (int)e }), "--Select Month--", new { @class = "form-control", @id = "Month1" })