Html.EnumDropdownListFor is it possible to order in alphabetical order?

I like the new Html.EnumDropdownListFor in MVC 5.1, and I see that I can specify the order of the values ​​in the Display attribute as follows:

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 shortsighted with localization. Is there a way to automatically create MVC for DDL in alphabetical order for me?

+6
source share
2 answers

I came up with a solution that gets 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); } 
+5
source

Is there a way to automatically assign MVC DDL in alphabetical order to me?

I don’t understand how to do this. None of the overloads accept any sorting options, such as ASC or DESC. It looks like you will have to either implement your own version of EnumDropDownListFor, potentially using EnumDropDownListFor, or use a javascript solution to sort the select element after the fact.

+1
source

Source: https://habr.com/ru/post/970585/


All Articles