默认在列表选择列表中设置选定的值

时间:2019-02-18 07:57:42

标签: c# html asp.net-mvc

我想默认在选择列表中设置一个选定的值。

我这里有此选择列表:

@{
List
<SelectListItem>
dateEcheancierCc = new List
<SelectListItem>
();
foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");
}
<div class="md-select px-0" style="min-width:0px">
   @Html.DropDownList("DateEche", dateEcheancierCc, new { @class = "form-conrol" })
</div>
}

在这里,我尝试设置默认选择“默认值”,但这对我不起作用,为什么?

以下是下拉列表:

 @Html.DropDownList("DateEche", dateEcheancierCc, new { @class = "form-conrol" })

4 个答案:

答案 0 :(得分:1)

dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch },"Value","Text","Selected-value-by-default");

更改为这样

dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });

确保您设置为“ Selected = true”的项目是列表中唯一的项目

我不知道您的规则,但是您可以这样尝试

例如:我有一个数组{“ Jeffrey”,“ John”,“ Joe”,“ Josh”},我想将Jeffrey设置为默认选择

if (dateEch == "Jeffrey")
    dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch, Selected = true });
else
    dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch });

答案 1 :(得分:0)

如果您的视图具有模型,则可以这样使用

                @Html.DropDownListFor(model => model.SelectedId, new SelectList(Model.SelectCollections, "Value", "Text", Model.ValueToBeSelectedInCollection))

答案 2 :(得分:0)

构建Selected=true时需要添加SelectListItem

foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(new SelectListItem() { Text = dateEch, Value = dateEch ,Selected = true });
}

答案 3 :(得分:0)

如下所示替换您的DropdownList,

<div class="md-select px-0" style="min-width:0px">
   @Html.DropDownList("DateEche",new SelectList(dateEcheancierCc,"Value","Text","Selected-value-by-default"), new { @class = "form-conrol" })
</div>

然后选择列表为

foreach (var dateEch in arrayDateEcheancierCc)
{
dateEcheancierCc.Add(
            new SelectListItem() { Text = dateEch, Value = dateEch }

            );
}

https://dotnetfiddle.net/RFgoD1

相关问题