您可以编写一个自定义的 html 助手,它将为当前模型生成一个下拉列表(当然假设这个模型是一个枚举):
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()
更新:
如果你想拥有模板中的所有代码,你也可以这样做:
@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)