c# - 如何在 MVC 的 DropDownList 中将默认值“0”设置为文本“选择”?
问题描述
下面是国家的下拉列表。我想要选定的文本“选择”正在工作。
@Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
new { @class = "form-control" })
现在我想为默认选中的文本“选择”设置值“0”。目前,“选择”的值为空白,如下所示。
我怎样才能做到这一点?值“选择”不在数据源中。我必须在 JQuery 中访问这个选定的值。
我已经尝试过这两个,但没有一个有效。
@Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { @class = "form-control", @selected = "0" })
和
@Html.DropDownList("ddlCountryName",
new SelectList(ViewBag.CountryName, "CountryId", "CountryName"),
"Select", new { @class = "form-control", @selected = "0" })
下面是 CountryName 值的控制器代码
ViewBag.CountryName = dbLMS.CountryMasters.Select(c => new { c.CountryId, c.CountryName }).OrderBy(c => c.CountryName).ToList();
解决方案
您可以执行以下操作:
选项1:
@{
var countrySelectList = new SelectList(ViewBag.CountryName, "CountryId", "CountryName");
List<SelectListItem> countrySelectListItems = countrySelectList.ToList();
countrySelectListItems.Insert(0, (new SelectListItem { Text = "Please select", Value = "0", Selected = true }));
}
@Html.DropDownList("ddlCountryName", countrySelectListItems , new { @class = "form-control" })
选项 2:
在控制器方法中:
List<SelectListItem> selectListItems = dbLMS.CountryMasters.Select(a => new SelectListItem()
{
Text = a.CountryName,
Value = a.CountryId
}).ToList();
selectListItems.Insert(0, new SelectListItem(){Text = "Selet Country", Value = "0", Selected = true});
ViewBag.CountrySelectList = selectListItems;
然后在视图中:
@Html.DropDownList("ddlCountryName", (List<SelectListItem>)ViewBag.CountrySelectList, new { @class = "form-control" })
推荐阅读
- mongodb - app.delete 不从集合中删除文档
- arrays - 如何在打字稿中的地图编号后添加“%”以进行前端反应?
- flutter - 如何检测颤振中的阻力速度?
- lua - 与 Lua 编程相关的帮助,其中 Basic Calculator 需要使用 3 个运算符加法、减法和乘法构建
- google-analytics - 有没有比这更好的教程在谷歌分析中使用谷歌标签管理器为客户 ID 创建自定义维度?
- javascript - 在 Firebase 托管上部署后,使用 Firebase 身份验证功能“signInWithEmailAndPassword”在 Web 上登录失败
- java - 如何在 openjdk:11 docker 镜像中安装 python?
- python - 使用 Python SDK 在 Azure 中创建虚拟机的用户名
- git - 从 git stash 返回到预览状态和提交中的顺序
- coldfusion - ColdFusion 8 中的过滤系统