【发布时间】:2019-07-08 12:34:32
【问题描述】:
我正在尝试在我的视图中创建一个 DropDownList,其中使用 ViewBag 将 SelectList 的数据传递给我的视图:
ViewBag.OtherKeysList = new SelectList(list, "OtherKey");
在我的视图中,我创建了一个 WebGrid,其中有一列表示此 DropDownList,如下所示:
grid.Column(columnName: "OtherKey", header: "OtherKey", format: @<text>@Html.DropDownList("OtherKey", (IEnumerable<SelectListItem>)ViewBag.OtherKeysList, new { @class = "extra-class" })</text>)))
但是,此列表仅使用列表中的第一项作为其默认值。如何将此列表的另一个值设置为其默认值?
更新:
当我尝试以下代码时:
public ActionResult EditMapping(int id)
{
var list = new ListWithDuplicates();
var v = (from a in dbProducts.MapperConfigs
where
a.MappingID.Equals(id)
select a
);
foreach (var item in v)
{
list.Add(item.OtherKey, item.OtherKeyType);
}
ViewBag.TotalRows = v.Count();
ViewBag.OtherKeysList = list.Select(x => new SelectListItem() { Text = x.Key, Value = x.Key, Selected = x.Key == "keyC" ? true : false });
ViewBag.MappingName = (from a in dbProducts.MappingNames
where
a.MappingID.Equals(id)
select a.Name
).First();
var data = v.ToList();
return View(data);
}
我得到以下结果:
然而这是配置的:
我想要实现的是:
Key1 : 具有默认值 keyA 的 DropDownlist
Key2 : 具有默认值 keyB 的下拉列表
Key3 : 具有默认值 keyC 的 DropDownlist
Key4 : 具有默认值 keyD 的下拉列表
【问题讨论】:
-
您想从模型中选择一个值还是一个固定值?
-
来自我的模型,但不是第一个。我想自己选一个。
-
@NielsStenden 你搞定了吗?
标签: asp.net select razor model-view-controller dropdown