以下是国家/地区的下拉列表。我想要选择的文本“选择”正在工作。
@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" })
new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)
你真的不需要Select的值。对于模型,请保留Required validation属性。
这将确保选择该值。这样你就不必检查后端。