您尚未展示如何填充此 TimeList 集合。像这样尝试,它应该可以工作:
public TimePlan TheTimePlan { get; set; }
public IEnumerable<SelectListItem> TimeList
{
get
{
var enumType = typeof(TimePlan);
var values = Enum.GetValues(enumType).Cast<TimePlan>();
var converter = TypeDescriptor.GetConverter(enumType);
return
from value in values
select new SelectListItem
{
Text = converter.ConvertToString(value),
Value = value.ToString(),
};
}
}
或者让它更通用一点,你可以编写一个可重用的助手:
public static IHtmlString DropDownListForEnum<TModel, TEnum>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var enumType = GetNonNullableModelType(metadata);
var values = Enum.GetValues(enumType).Cast<TEnum>();
var converter = TypeDescriptor.GetConverter(enumType);
var items =
from value in values
select new SelectListItem
{
Text = converter.ConvertToString(value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
return htmlHelper.DropDownListFor(expression, items);
}
然后您的模型只能包含 Enum 值:
public TimePlan TheTimePlan { get; set; }
并在您看来使用助手:
@Html.DropDownListForEnum(x => x.TheTimePlan)