개발/C# .NET

[MVC] EnumDropDownList

xwing 2011. 6. 22. 14:58

MVC 에서 Enum Type을 DropDownList에 바인딩 하는 코드이다.

  1. public static class CommonUtil
  2.     {
  3.         private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };
  4.  
  5.         public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, SelectListItem firstSelectItem)
  6.         {
  7.             ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
  8.             Type enumType = GetNonNullableModelType(metadata);
  9.             IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
  10.  
  11.             TypeConverter converter = TypeDescriptor.GetConverter(enumType);
  12.  
  13.             IEnumerable<SelectListItem> items =
  14.                 from value in values
  15.                 select new SelectListItem
  16.                 {
  17.                     Text = converter.ConvertToString(value),
  18.                     Value = value.ToString()
  19.                 };
  20.  
  21.             if (metadata.IsNullableValueType)
  22.             {
  23.                 items = SingleEmptyItem.Concat(items);
  24.             }
  25.  
  26.             
  27.             if (firstSelectItem != null)
  28.             {
  29.                 firstSelectItem.Selected = true;
  30.                 SelectListItem[] newItem = new SelectListItem[1];
  31.                 newItem[0] = firstSelectItem;
  32.                
  33.                 items = newItem.Concat(items);
  34.             }
  35.                         
  36.             MvcHtmlString html = htmlHelper.DropDownList("DDL" + metadata.PropertyName, items);
  37.  
  38.             return html;
  39.         }
  40.  
  41.         
  42.         private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
  43.         {
  44.             Type realModelType = modelMetadata.ModelType;
  45.  
  46.             Type underlyingType = Nullable.GetUnderlyingTy

  1. @Html.EnumDropDownListFor(model => model.EnumColor, new SelectListItem { Text = "--", Value = "" })
 

'개발 > C# .NET' 카테고리의 다른 글

C# machine key 생성하기  (0) 2011.07.05
C# 한글깨짐 처리  (1) 2011.04.20
자동 생성된 Machinekey 읽기  (0) 2011.04.15