我有枚举的字符串值(在属性中),并希望有html帮助器来显示它。不幸的是,我需要使用指定的值作为ddl中的键。因此,它不会选择存储在ViewModel中的项目。怎么办?
示例枚举
public enum StatusEnum
{
[Value("AA")]
Active,
[Value("BB")]
Disabled
}
视图模型
public class UserViewModel
{
public StatusEnum Status { get; set; }
}
查看
@Html.DropDownListForEnum(x => x.Status, new {})
DropDownListForEnum帮助
public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
IEnumerable<SelectListItem> items = Enum.GetNames(typeof(TEnum))
.Select(n => (TEnum)Enum.Parse(typeof(TEnum), n))
.Select(e => new SelectListItem() {
Text = e.ToString(),
Value = EnumExtension.GetValue(e).ToString(),
Selected = EnumExtension.GetValue(e) == EnumExtension.GetValue(metadata.Model)
})
.ToList();
return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
}
答案 0 :(得分:0)
不是将IEnumerable<SelectListItem>
传递到下拉菜单,而是手动创建并填充SelectList
并传递它,它将起作用:
public static MvcHtmlString DropDownListForEnum<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var items = Enum.GetNames(typeof(TEnum))
.Select(n => (TEnum)Enum.Parse(typeof(TEnum), n))
.Select(e => new
{
Id = Convert.ToInt32(e),
Text = e.ToString(),
Value = EnumExtension.GetValue(e).ToString(),
Selected = EnumExtension.GetValue(e) == EnumExtension.GetValue(metadata.Model)
})
.ToList();
var selectList = new SelectList(items, "Text", "Value", selectedValue: items.Find(i => i.Selected).Text);
return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}