public static class HTMLHelpExprettions { private static Type GetNonNullableModelType(ModelMetadata modelMetadata) { Type realModelType = modelMetadata.ModelType; Type underlyingType = Nullable.GetUnderlyingType(realModelType); if (underlyingType != null) { realModelType = underlyingType; } return realModelType; } private static Type GetEnumTypeFromAttribute(Expression> expression) { MemberInfo propertyInfo = ((expression.Body as MemberExpression).Member as MemberInfo); if (propertyInfo == null) throw new ArgumentException("The lambda expression 'property' should point to a valid Property"); EnumDataTypeAttribute attr = Attribute.GetCustomAttribute(propertyInfo, typeof(EnumDataTypeAttribute)) as EnumDataTypeAttribute; if (attr == null) throw new ArgumentException("式木で指定されたメンバーにはEnumDataTypeが指定されていません"); return attr.EnumType; } private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } }; //エイリアス public static string DisplayEnumFor(this HtmlHelper htmlHelper,Expression> expression) { return GetEnumDescription(expression.Compile()(htmlHelper.ViewData.Model),GetEnumTypeFromAttribute(expression)); } private static string GetEnumDescription(int enumValue, Type enumType) { FieldInfo fi = enumType.GetField(enumType.GetEnumName(enumValue)); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if ((attributes != null) && (attributes.Length > 0)) return attributes[0].Description; else return enumType.GetEnumName(enumValue); } /// /// EnumDataTypeAttributeで情報が付け加えられたint型のプロパティーをドロップダウンに変換します。 /// /// /// /// /// /// /// public static MvcHtmlString EnumDropDownListFor( this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes = null) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); Type enumType = GetEnumTypeFromAttribute(expression); IEnumerable values = Enum.GetValues(enumType).Cast(); IEnumerable items = values.Select(value=>new SelectListItem { Text = GetEnumDescription(value,enumType), 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, htmlAttributes); } }