Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.EnumDropdownListFor can I order alphabetically?

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?

like image 529
jhilden Avatar asked Jun 09 '14 19:06

jhilden


2 Answers

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);
}
like image 181
bradlis7 Avatar answered Oct 19 '22 23:10

bradlis7


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.

like image 23
Jakotheshadows Avatar answered Oct 20 '22 00:10

Jakotheshadows