Skip to content

Instantly share code, notes, and snippets.

@archer884
Created October 16, 2014 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save archer884/305e8ce162297270e1ca to your computer and use it in GitHub Desktop.
Save archer884/305e8ce162297270e1ca to your computer and use it in GitHub Desktop.
Victory is mine.
public static MvcHtmlString SortedEnumDropDownListFor<TModel, TEnum>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression,
bool descending = false)
{
var propertyInfo = (expression.Body as MemberExpression).Member as PropertyInfo;
var options = Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(code => new SelectListItem()
{
Selected = code.Equals((TEnum)propertyInfo.GetValue(htmlHelper.ViewData.Model)),
Text = code.ToString(),
Value = code.ToString(),
});
options = descending
? options.OrderByDescending(option => option.Text)
: options.OrderBy(option => option.Text);
return htmlHelper.DropDownListFor(expression, options);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment