MVC/EF 应用程序的 DropDownList 中未选择任何项目

No item selected in DropDownList in MVC/EF application

现在,我正在尝试为使用下拉列表的 MVC 应用程序创建一个编辑页面,允许用户编辑员工的位置。我考虑了两种情况:一种是员工没有固定位置,另一种是员工已经有指定位置。在第二种情况下,我希望编辑页面中的下拉列表自动在列表中选择当前位置。该列表已成功创建,但它默认为 SelectList 中的第一个值(在本例中为空字符串),而不是当前选定的值。本案例控制器代码如下:

var pairs = db.Locations.Select(x => new { value = x.LocationID, text = x.City }).ToList();
            pairs.Insert(0, (new {value = 0, text = ""}));
            SelectList Locations = new SelectList(pairs,
            "value", "text", pairs.First(x=> x.value == employee.Location.LocationID));
            foreach (SelectListItem item in Locations)
            {
                item.Selected = false;
            }
            foreach (SelectListItem item in Locations)
            {
                if (item.Value == (employee.Location.LocationID.ToString()))
                {
                    Debug.Print("Match Found");
                    item.Selected = true;
                    break;
                }

            }

            ViewBag.Locations = Locations;

请注意,现在我正在明确枚举列表,并将所需值标记为选中。最初,我对采用 "selectedValue" 参数的 SelectList 构造函数使用了重载,但这也不起作用。还要注意打印语句:当 运行 时,确实打印了该行,这意味着找到并标记了匹配值。它根本不会在页面上这样显示。

视图中的代码如下:

<div class="form-group">
        @Html.Label("Location", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("location", ViewBag.Locations as IEnumerable<SelectListItem>)
        </div>
    </div>

有什么我遗漏的吗?

谢谢!

我很确定您可以大大简化您的代码并获得您想要的相同结果。

您可以在您的控制器中使用它

var Locations = new SelectList(db.Locations, "LocationID", "City");
ViewBag.Locations = Locations;

在您看来只需使用 DropDownListFor

@Html.DropDownListFor(m => m.Location.LocationID, (SelectList)ViewBag.Locations)