asp.net - 如何使用 ASP.NET MVC 在 View 中设置 DropDownList 的默认值?
问题描述
我正在尝试在我的视图中创建一个 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 的下拉列表
Key2:具有默认值 keyB 的下拉列表
Key3 :具有默认值 keyC 的下拉列表
Key4 :具有默认值 keyD 的下拉列表
解决方案
我假设您可以通过操作绑定到 SelectList 的默认 SelectListItem 来实现您想要的结果。list
var defaultItem = new SelectListItem()
{
Value = 1,
Text = "Default Item",
Selected = true
};
推荐阅读
- java - 使用 Java 从 td href 元素中提取链接
- postgresql - Big Sur 失败时的 PostgreSQL 安装
- jquery - JQuery禁用提交按钮,直到表单完全填满
- android - 当应用程序进入后台时,如何在屏幕中设置位图或可绘制
- python - ModuleNotFoundError:没有名为“jqmcvi”的模块
- android - Android TV:回收站视图不滚动
- java - 为什么Java中没有删除成员字段的这种通用类型信息?
- merge - jq在数组中查找后合并对象
- react-native - 为每个用户发送博览会通知和广播通知
- reactjs - 是否可以下载 create-react-app 应用程序的源文件/代码?