Skip to content

Instantly share code, notes, and snippets.

@diego-augusto
Created March 3, 2018 16:13
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 diego-augusto/f1aa18b73b3184bd251fd0594089ecbd to your computer and use it in GitHub Desktop.
Save diego-augusto/f1aa18b73b3184bd251fd0594089ecbd to your computer and use it in GitHub Desktop.
Custom DropDownListFor for nullable types
private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
{
Type realModelType = modelMetadata.ModelType;
Type underlyingType = Nullable.GetUnderlyingType(realModelType);
if (underlyingType != null)
{
realModelType = underlyingType;
}
return realModelType;
}
public static string GetEnumDescription<TEnum>(TEnum value)
{
var field = value.GetType().GetField(value.ToString());
var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : value.ToString();
}
public static MvcHtmlString CustomEnumDropDownListFor<TModel, TEnum>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetNonNullableModelType(metadata);
var values = Enum.GetValues(enumType).Cast<TEnum>();
var items =
values.Select(
value =>
new SelectListItem
{
Text = GetEnumDescription(value),
Value = value.ToString(),
Selected = false
});
var attributes = System.Web.Mvc.HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
return htmlHelper.DropDownListFor(expression, items, "Selecione...", attributes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment