【问题标题】:How to set default value "0" to text "Select" in DropDownList in MVC?如何在 MVC 的 DropDownList 中将默认值“0”设置为文本“Select”?
【发布时间】:2019-02-12 11:43:01
【问题描述】:

下面是国家的下拉列表。我想要选定的文本“选择”正在工作。

@Html.DropDownList("ddlCountryName", 
 new SelectList(ViewBag.CountryName, "CountryId", "CountryName"), 
 new { @class = "form-control" })

现在我想为默认选中的文本“选择”设置值“0”。目前“Select”的值为空,如下所示。

我该怎么做?值“选择”不在数据源中。我必须在 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();

【问题讨论】:

  • SelectList 有参数object selectedValue。你说的是这个吗?我看不到您附加的图片。
  • 你试过删除@selected = "0"吗?
  • @er-sho 我试过了,但它不起作用,因为“选择”和“0”都不是数据源的一部分。
  • @SurajKumar,告诉我你如何从控制器方法绑定你的国家名称
  • @er-sho 我已将控制器代码添加到问题中。

标签: c# selectedvalue


【解决方案1】:

你可以这样做:

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

【讨论】:

  • @SurajKumar 哦!我错过了国家名称后的"。你也应该注意到这一点。请使用更新后的代码。 Surly 现在可以使用了。
  • Selected = true 应该是 ,Selected = true。你缺少逗号。
  • 是的!谢谢你的通知。它现在肯定会起作用。
  • 它工作正常,如果不能从您的解决方案中得到更短的解决方案,我会在一段时间后接受它。
  • 好的!等到那时没问题:)
【解决方案2】:

new SelectList(ViewBag.CountryName, "CountryId", "CountryName", //Default value)

【讨论】:

  • @SurajKumar 你试过用 0 我把 //Default Value 放在哪里?
  • 我必须为“选择”设置“0”而不是选择的值。而“0”是“Select”的值。
【解决方案3】:

您真的不需要 Select 的值。对于模型,保留Required 验证属性。

这将确保选择该值。这样您就不必检查后端。

【讨论】:

    猜你喜欢
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2010-09-23
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-22
    相关资源
    最近更新 更多