MVC DropDownListFor - SelectedItem 不适用于嵌套值

MVC DropDownListFor - SelectedItem not working for nested value

在我的 C# MVC4 .NET WebApplication 中,我有一个具有以下方法调用的自定义助手:

@Custom.DropDownListFor(m => m.CategorySetups[categoryId].Gender, CategoryHelper.Genders, new { @class = "form-control" })

内部类似于:

@Html.DropDownListFor(expression, new SelectList(items, "Value", "Text"))

因为我在这里覆盖了 SelectListItem。

此调用不是 select 存储在

中的呈现视图中的值
m.CategorySetups[categoryId].Gender

如果我这样调用方法(不在同一个视图中):

@Custom.DropDownListFor(m => m.Gender, CategoryHelper.Genders, new { @class = "form-control" })

呈现的 HTML 具有标记为

的正确值
<option value="Under15" selected>Under15</option>

所以我的猜测是,这与嵌套 select 的 属性 有关,但我没有看到它。

从调试中我可以看到,

m.CategorySetups[categoryId].Gender

在应该呈现 select 时设置了正确的值。

注意:不确定这是否会导致问题(因为它正在工作的第二种方式)但绑定值类型是枚举。

更新评论:

实现如下:

 public static readonly List<SelectListItem<ClassificationType>> ClassificationTypes = new List<SelectListItem<ClassificationType>>
        {
            new SelectListItem<ClassificationType> {Text = @"please select...", Value = ClassificationType.NotSet},
            new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under13), Value = ClassificationType.Under13},
            new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under15), Value = ClassificationType.Under15},
            new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Under18), Value = ClassificationType.Under18},
            new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Over30), Value = ClassificationType.Over30},
            new SelectListItem<ClassificationType> {Text = EnumParser.GetString(ClassificationType.Open), Value = ClassificationType.Open}
        };

带参数object selectedValueSelectList contructor has an overload,需要指定选择的值,一般DropDownListFor()我们是这样写的:

@Html.DropDownListFor(m=>m.Gender,
                     new SelectList(Model.Genders,"Id","Value",Model.Gender),
                     new { @class = "form-control" })

更新:

在你的情况下你可以这样做:

@Custom.DropDownListFor(m => m.CategorySetups[categoryId].Gender, 
                        new SelectList(CategoryHelper.Genders,"Value","Text",Model.CategorySetups[categoryId].Gender), 
                        new { @class = "form-control" })

还有一点,当您通过 Enum 填充项目时,您可以使用我在

中发布的扩展方法