Created
January 28, 2014 13:39
-
-
Save jasmin-mistry/8667815 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static partial class MyEnumDropDownList | |
{ | |
#region Enum DropDown | |
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, | |
Expression<Func<TModel, TEnum>> expression) | |
{ | |
return EnumDropDownListFor(htmlHelper, expression, null); | |
} | |
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, | |
Expression<Func<TModel, TEnum>> expression, string optionLabel) | |
{ | |
return EnumDropDownListFor(htmlHelper, expression, optionLabel, null); | |
} | |
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, | |
Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes) | |
{ | |
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); | |
Type enumType = GetNonNullableModelType(metadata); | |
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>(); | |
IEnumerable<SelectListItem> items = from value in values | |
select new SelectListItem | |
{ | |
Text = GetEnumDescription(value), | |
Value = value.ToString(), | |
Selected = value.Equals(metadata.Model) | |
}; | |
// If the enum is nullable, add an 'empty' item to the collection | |
if (metadata.IsNullableValueType) | |
items = SingleEmptyItem.Concat(items); | |
return htmlHelper.DropDownListFor(expression, items, optionLabel, htmlAttributes); | |
} | |
public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, string name, TEnum selectedValue) | |
{ | |
return EnumDropDownList(htmlHelper, name, selectedValue, null); | |
} | |
public static MvcHtmlString EnumDropDownList<TEnum>(this HtmlHelper htmlHelper, string name, TEnum selectedValue, object htmlAttributes) | |
{ | |
IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)) | |
.Cast<TEnum>(); | |
IEnumerable<SelectListItem> items = from value in values | |
select new SelectListItem | |
{ | |
Text = value.ToString(), | |
Value = value.ToString(), | |
Selected = (value.Equals(selectedValue)) | |
}; | |
return htmlHelper.DropDownList(name, items, htmlAttributes); | |
} | |
#endregion | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment