首页 > 解决方案 > 如何在 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();

标签: c#selectedvalue

解决方案


您可以执行以下操作:

选项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" })

推荐阅读