我正在尝试使用通过ViewBag传递到我的View的SelectList的数据在View中创建一个DropDownList:
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的下拉列表
答案 0 :(得分:0)
我假设您可以通过操作绑定到 SelectList 的list
中的默认 SelectListItem 来获得所需的结果。
var defaultItem = new SelectListItem()
{
Value = 1,
Text = "Default Item",
Selected = true
};