MVC3下拉列表值未填充在编辑器模板中

时间:2012-06-19 16:48:33

标签: asp.net-mvc-3 data-binding drop-down-menu

我有一个带下拉列表的编辑器模板:

 @Html.DropDownListFor(m => m.AdmissionState, new List<SelectListItem>()
                                                   {
                                                       new SelectListItem()
                                                           {
                                                               Text = "1",
                                                               Value = "1"
                                                           },
                                                       new SelectListItem()
                                                           {
                                                               Text = "2",
                                                               Value = "2"
                                                           },
                                                       new SelectListItem()
                                                           {
                                                               Text = "3",
                                                               Value = "3"
                                                           },                   
                                                   }, "- Select -")

我从视图中调用它:

@Html.EditorFor(m => m.Licenses)

在控制器中我有以下代码:

profile.Licenses.Add(new AttorneyLicenseModel()
        {
            AdmissionDate = "06/14/2012",
            AdmissionState = "2",
            AdmissionNumber = "asd",
        });
        profile.Licenses.Add(new AttorneyLicenseModel()
        {
            AdmissionDate = "07/16/2012",
            AdmissionState = "5",
            AdmissionNumber = "qwe",
        });

对于每个许可证,我看到的字段包含从模型填充的数据,但不会显示下拉列表 - 检查默认值。我究竟做错了什么?当然,带有值的代码非常简单

1 个答案:

答案 0 :(得分:1)

试试这样:

@Html.DropDownListFor(
    m => m.AdmissionState, 
    new SelectList(
        new[] 
        {
            new { Value = "1", Text = "1" },
            new { Value = "2", Text = "2" },
            new { Value = "3", Text = "3" },
        }, 
        "Value", 
        "Text", 
        Model.AdmissionState
    ),
    "- Select -"
)

如果您有兴趣了解我的代码为什么有效,那么您可以阅读我昨天提供的以下答案:ASP.NET MVC DropDownListFor not selecting value from model