具有自定义值(存储在属性中)的枚举的DropDownListFor不会选择项目

时间:2014-12-19 15:25:13

标签: asp.net-mvc enums html-helper html.dropdownlistfor modelbinders

我有枚举的字符串值(在属性中),并希望有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);
}

1 个答案:

答案 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);
}