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<TModel>(Expression<Func<TModel, int>> 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<TModel>(this HtmlHelper<TModel> htmlHelper,Expression<Func<TModel, int>> 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);
}
/// <summary>
/// EnumDataTypeAttributeで情報が付け加えられたint型のプロパティーをドロップダウンに変換します。
/// </summary>
/// <typeparam name="TModel"></typeparam>
/// <param name="htmlHelper"></param>
/// <param name="expression"></param>
/// <param name="model"></param>
/// <param name="htmlAttributes"></param>
/// <returns></returns>
public static MvcHtmlString EnumDropDownListFor<TModel>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, int>> expression, object htmlAttributes = null)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
Type enumType = GetEnumTypeFromAttribute(expression);
IEnumerable<int> values = Enum.GetValues(enumType).Cast<int>();
IEnumerable<SelectListItem> 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);
}
}