如何使用 ASP.NET MVC 为 View 中的 DropDownList 设置不同的预配置默认值?

How to set different preconfigured default values for DropDownList in View using ASP.NET MVC?

我创建了一个程序,它能够为彼此配置 2 个键,例如:

Key 1 = key a,
key 2 = key b,
key 3 = key c,
etc

配置页面如下:

当按下提交按钮时,它会将配置发送到数据库:

这工作正常,但现在我正在尝试为配置创建一个编辑页面。在此配置页面中,我使用从数据库获取配置并将其放入 WebGrid 的查询:

查询:

var v = (from a in dbProducts.MapperConfigs
                 where
                    a.MappingID.Equals(id)
                 select a
                   );

这将获得整个配置,在 WebGrid 的左侧我只放置键:key1、key2、key3、key4 等。但在右侧我希望用户可以选择哪个键连接到 key1、key2、key3 等。因此我使用下拉列表,但是这个下拉列表由 SelectListItem 填充,代码如下:

控制器:

 foreach (var item in v)
 {
      list.Add(item.OtherKey, item.OtherKeyType);
 }

 ViewBag.OtherKeysList = new SelectList(list, "OtherKey");

视图中的 WebGrid:

 grid.Column(columnName: "OtherKey", header: "OtherKey", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))

这将导致将所有键、keyA、KeyB、KeyC 放入 DropDownList 中,但不是按照配置的那样。我正在尝试获取我之前配置的下拉列表中的默认值。

有人对如何实现这一点有建议吗?

提前致谢

你的线路

    ViewBag.OtherKeysList = new SelectList(list, "OtherKey");

不起作用,因为 Selectlist 构造函数的第二个参数是默认值。

当您使用字典(list 变量)作为源时,您必须使用字典中的实际项目作为 SelectedValue.

这可行:

    ViewBag.OtherKeysList = new SelectList(list, list.Single(i => i.Key == "KeyB"));

这里的 "KeyB" 是选择并保存在数据库中的密钥。