MVC 에서 Enum Type을 DropDownList에 바인딩 하는 코드이다.
- public static class CommonUtil
- {
- private static readonly SelectListItem[] SingleEmptyItem = new[] { new SelectListItem { Text = "", Value = "" } };
- public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, SelectListItem firstSelectItem)
- {
- ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
- Type enumType = GetNonNullableModelType(metadata);
- IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();
- TypeConverter converter = TypeDescriptor.GetConverter(enumType);
- IEnumerable<SelectListItem> items =
- from value in values
- select new SelectListItem
- {
- Text = converter.ConvertToString(value),
- Value = value.ToString()
- };
- if (metadata.IsNullableValueType)
- {
- items = SingleEmptyItem.Concat(items);
- }
- if (firstSelectItem != null)
- {
- firstSelectItem.Selected = true;
- SelectListItem[] newItem = new SelectListItem[1];
- newItem[0] = firstSelectItem;
- items = newItem.Concat(items);
- }
- MvcHtmlString html = htmlHelper.DropDownList("DDL" + metadata.PropertyName, items);
- return html;
- }
- private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
- {
- Type realModelType = modelMetadata.ModelType;
- Type underlyingType = Nullable.GetUnderlyingTy
- @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 |