[英]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等。因此,我使用了一个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中,但未按配置进行。 我试图在我的下拉列表中获取默认值,就像之前配置的那样。
有没有人建议如何实现这一目标?
提前致谢
你的线
ViewBag.OtherKeysList = new SelectList(list, "OtherKey");
不起作用,因为Selectlist构造函数的第二个参数是默认值。
在为源使用字典( 列表变量)时,必须将字典中的实际项目用作SelectedValue 。
这将工作:
ViewBag.OtherKeysList = new SelectList(list, list.Single(i => i.Key == "KeyB"));
在这种情况下,“ KeyB”是已选择并保存在数据库中的密钥。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.