Anup
Anup

Reputation: 9738

DropDown with Enum - Value attribute for Select

I am having following DropDown which populates from Enum.

@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
}

The output of html is like this <option>January</option>

I want value of the month in numeric like this <option value="1">January</option>

How will the value attribute come with numeric values?

Upvotes: 1

Views: 1117

Answers (1)

opewix
opewix

Reputation: 5083

You have to specify Value in new SelectListItem { Text = e, Value = enumValue }

EDIT

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" })

Upvotes: 1

Related Questions