I'm working with ASP.NET MVC3
and I'm trying to fill a DropDownList
with an Enum
.
My problem is that the enum begins at -1
and the DropDownList
is correctly filled, but the first item (whichever has the -1
value) is always the last item of my DropDownList
; however, I need it in first position.
Here is my .cshtml
@Html.DropDownListFor(m => m.MyEnumMax, new SelectList(Enum.GetValues(typeof(MyEnum))), new { @id = "myId", @class = "myClass" })
Here, MyEnumMax
is a string property representing a MyEnum
member (maybe is this the problem ? However, it really helps me elsewhere in the project to have this string property)
and the enum just looks like
public enum MyEnum
{
Undefined = -1,
Member1,
Member 2
}
So in my view, I have my ddl lloks like :
whereas I need :
I tried some OrderBy(x => x.Value)
but it doesn't care and still displays Undefined at last position.
Any help (with code sample) appreciated
You just need to order Enum by its int value,
code:
@Html.DropDownListFor(m => m.TestEnumValue,Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.OrderBy(e => (int)e)
.Select(e => new SelectListItem
{
Text = e.ToString(),
Value = ((int)e).ToString()
} ))
You also need to cast GetValues to get typed version: GetValues(typeof(MyEnum)).Cast<MyEnum>
result: