I'm using ASP.NET MVC3 and I'd like to populate a DropDownList with enum values and select one or more option(s).
I customized the DropDownList in order to it looks like to a "CheckedDropDownList", and, in a very basic Edit
form, I need to check the actual values.
Here is how my Enum is constructed :
public enum MyEnum
{
[Display(Name = "Undefined")]
UNDEFINED = -1, //I really need this "detail"
[Display(Name = "First Value")]
VALUE1,
[Display(Name = "Second Value")]
VALUE2
[Display(Name = "Other")]
OTHER,
}
I'm also using this ToLocalizedSelectList<>()
method, which I tried to adapt from this SO question, but I'm unable to modifiy it to accept multiple selected values.
public static SelectList ToLocalizedSelectList<T>(this T enumeration, string selected)
{
var source = Enum.GetValues(typeof(T)).Cast<T>().OrderBy(x => x); //I always need UNDEFINED as first element
var items = new Dictionary<object, string>();
var displayAttributeType = typeof(DisplayAttribute);
foreach (var value in source)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DisplayAttribute attrs = (DisplayAttribute)field.GetCustomAttributes(displayAttributeType, false).FirstOrDefault();
items.Add(value, attrs != null ? attrs.GetName() : value.ToString());
}
return new SelectList(items, "Key", "Value", selected);
}
Here is how I use it :
@Html.DropDownListFor(m => m.EnumValues,
AttributesHelperExtension.ToLocalizedSelectList<MyEnum>(MyEnum.UNDEFINED, Enum.GetName(typeof(MyEnum), Model.EnumValues.First())
Enum.GetName(typeof(MyEnum), Model.EnumValues.First())),
new { @id = "ddlEnumValue" }
)
With EnumValues
is defined as :
public MyEnum[] EnumValues { get; set; }
The problem is, I think, on the third argument, I need to pass Model.EnumValues
and not Model.EnumValues.First()
, which always preselect only the first item of my MyEnum
enumeration.
The second argument could also be a problem, because ToLocalizedSelectList<>()
needs a this MyEnum enumeration as a first parameter, so I passed it the first item of my enum, but I'm not sure this is a good solution.
How could I transform this ToLocalizedSelectList<>()
method in order to it accept multiple selected values, and how could I use it in an @Html.DropDownListFor
(or @Html.ListBoxFor
) ?
Thanks a lot
Just FYI, I also tried this code :
@Html.ListBoxFor(m => m.EnumValues,
new SelectList(Enum.GetValues(typeof(MyEnum))
.Cast<MyEnum>()
.OrderBy(e => (int)e)
), new { @id = "ddlMyEnum" }
)
and it pre-select the good valueS, however, it displays enum names, like UNDEFINED
, VALUE1
instead of their Display Name
attribute (Undefined
, First Value
) etc...