你这样做是不对的。应该为空的不是 TimeList,而是应该存储所选项目的 TimePlan 属性。以下是您的视图模型中应该包含的内容:
public TimePlan? TheTimePlan { get; set; }
public IEnumerable<SelectListItem> TimeList
{
get
{
var enumType = typeof(TimePlan);
var values = Enum.GetValues(enumType).Cast<TimePlan>();
return
from value in values
select new SelectListItem
{
Text = Enum.GetName(typeof(TimePlan), value),
Value = value.ToString(),
};
}
}
然后,在您的视图中,您将拥有:
@Html.DropDownListFor(model => model.TheTimePlan, Model.TimeList, "Please select...")
更新:
如果你想创建一个自定义的 html 帮助器,你可以这样做:
public static IHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression, string optionLabel)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var enumType = GetNonNullableModelType(metadata);
var values = Enum.GetValues(enumType).Cast<TEnum>();
var items =
from value in values
select new SelectListItem
{
Text = Enum.GetName(enumType, value),
Value = value.ToString(),
Selected = value.Equals(metadata.Model)
};
return htmlHelper.DropDownListFor(expression, items, optionLabel);
}
private static Type GetNonNullableModelType(ModelMetadata modelMetadata)
{
Type modelType = modelMetadata.ModelType;
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
return modelType;
}
然后,在您的视图中,您将拥有:
@Html.DropDownListForEnum(model => model.TheTimePlan, "Please select...")