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

时间:2019-07-09 07:37:59

标签: c# asp.net model-view-controller dropdown selectlist

我创建了一个程序,该程序能够相互配置2个键,例如:

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

具有以下配置页面:

enter image description here

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

enter image description here

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

enter image description here

查询:

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

这将获得整个配置,在WebGrid的左侧,我只放置了键:key1,key2,key3,key4等。但是在右侧,我希望用户可以选择要连接的键到key1,key2,key3等。因此,我使用dropdownlist,但是此dropdownlist由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中,但不按配置。我正尝试在下拉列表中获取以前配置的默认值。

有人建议如何实现吗?

预先感谢

1 个答案:

答案 0 :(得分:0)

您的行

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

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

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

这将起作用:

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

在这种情况下,“ KeyB”是已选择并保存在数据库中的密钥。