Created
September 3, 2012 04:43
-
-
Save kmoormann/3606767 to your computer and use it in GitHub Desktop.
MVC Enum Helper (via http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx)
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Web.Mvc.Html; | |
namespace MyProject.Helpers | |
{ | |
public static class EnumHelpers | |
{ | |
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression) | |
{ | |
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); | |
Type enumType = GetNonNullableModelType(metadata); | |
IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>(); | |
IEnumerable<SelectListItem> items = | |
values.Select(value => new SelectListItem | |
{ | |
Text = value.ToString(), | |
Value = value.ToString(), | |
Selected = value.Equals(metadata.Model) | |
}); | |
if (metadata.IsNullableValueType) | |
{ | |
items = SingleEmptyItem.Concat(items); | |
} | |
return htmlHelper.DropDownListFor( | |
expression, | |
items | |
); | |
} | |
private static Type GetNonNullableModelType(ModelMetadata modelMetadata) | |
{ | |
Type realModelType = modelMetadata.ModelType; | |
Type underlyingType = Nullable.GetUnderlyingType(realModelType); | |
if (underlyingType != null) | |
{ | |
realModelType = underlyingType; | |
} | |
return realModelType; | |
} | |
private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } }; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks to http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx for the blog post. Just posting this on gist so i can reuse it.