I love the new Html.EnumDropdownListFor in MVC 5.1, and I see that I can specify the order of values within the Display attribute like this:
public enum AssignableDataFieldEnum
{
[Display(Name = "Code Value", Order=1)]
CodeValue = 1,
[Display(Name = "Final Digit", Order=2)]
FinalDigit = 2,
[Display(Name = "Group Number", Order=3)]
GroupNumber = 3,
[Display(Name = "Sequence Number", Order=4)]
SequenceNumber = 4
}
This solution seems short sighted with localization. Is there a way to automatically have MVC order the DDL alphabetically for me?
I came up with a solution that gets the Enum values, sorts them, and then makes a call to HtmlHelper.DropDownListFor()
.
public static MvcHtmlString EnumSortedDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel = null, IDictionary<string, object> htmlAttributes = null) {
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var selectList = EnumHelper.GetSelectList(metadata.ModelType).OrderBy(i => i.Text).ToList();
if (!String.IsNullOrEmpty(optionLabel) && selectList.Count != 0 && String.IsNullOrEmpty(selectList[0].Text)) {
selectList[0].Text = optionLabel;
optionLabel = null;
}
return htmlHelper.DropDownListFor(expression, selectList, optionLabel, htmlAttributes);
}
Is there a way to automatically have MVC order the DDL alphabetically for me?
I don't see how. None of the overloads appear to take any form of sorting parameters such as ASC or DESC. It seems like you'd either have to implement your own version of EnumDropDownListFor, potentially using EnumDropDownListFor itself, or use a javascript solution to sort the select element after the fact.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With