에게 당신을 "어떻게 열거 형에서 선택 목록을 생성" 현재 모델의 드롭 다운 목록을 생성하는 사용자 정의 html 도우미를 작성할 수 있습니다 (이 모델은 물론 enum 임).
public static class HtmlExtensions
{
public static IHtmlString DropDownListForEnum(this HtmlHelper htmlHelper)
{
var model = htmlHelper.ViewData.Model;
if (model == null)
{
throw new ArgumentException("You must have a model in order to use this method");
}
var enumType = model.GetType();
if (!enumType.IsEnum)
{
throw new ArgumentException("This method works only with enum types.");
}
var fields = enumType.GetFields(
BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
);
var values = Enum.GetValues(enumType).OfType<object>();
var items =
from value in values
from field in fields
let descriptionAttribute = field
.GetCustomAttributes(
typeof(DescriptionAttribute), true
)
.OfType<DescriptionAttribute>()
.FirstOrDefault()
let description = (descriptionAttribute != null)
? descriptionAttribute.Description
: value.ToString()
where value.ToString() == field.Name
select new { Id = value, Name = description };
var selectList = new SelectList(items, "Id", "Name", model);
return htmlHelper.DropDownList("", selectList);
}
}
,
다음 템플릿에 단순히이 도우미를 호출
@Html.DropDownListForEnum()
UPDATE
:
@using System.ComponentModel
@using System.Reflection
@using System.Linq;
@model object
@{
var model = Html.ViewData.Model;
if (model == null)
{
throw new ArgumentException("You must have a model in order to use this template");
}
var enumType = model.GetType();
if (!enumType.IsEnum)
{
throw new ArgumentException("This method works only with enum types.");
}
var fields = enumType.GetFields(
BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public
);
var values = Enum.GetValues(enumType).OfType<object>();
var items =
from value in values
from field in fields
let descriptionAttribute = field
.GetCustomAttributes(
typeof(DescriptionAttribute), true
)
.OfType<DescriptionAttribute>()
.FirstOrDefault()
let description = (descriptionAttribute != null)
? descriptionAttribute.Description
: value.ToString()
where value.ToString() == field.Name
select new { Id = value, Name = description };
var selectList = new SelectList(items, "Id", "Name", model);
}
@Html.DropDownList("", selectList)
:
그리고 당신도 그렇게 할 수있는 템플릿에있는 모든 코드를 원한다면
귀하의 질문이 명확하지 않습니다. 모델의 예를 제공하고이 템플릿을 어떻게 사용하려고합니까? –
이것은 enum의 UIHint입니다. – Mediator