Html.DropDownListFor 添加预选值时值重复

Html.DropDownListFor value duplicates when add a Preselect value

我的代码是这样的

List<String> ddlData = new List<string>();
ddlData.Add("--Select--");
ddlData.Add("Manager");

@Html.DropDownListFor(n => n.myddl, new SelectList(ddlData), "Manager", new { @class = "custom-select" })

我觉得一切都很好,但是当 Dropdown 加载时,它加载了两个“管理器”。我只想填充 ddlData 个项目并预选“经理”。

如果 ddlData 是在视图中定义的,您可以尝试:

@Html.DropDownListFor(m => ddlData,
    ddlData.Select(d => { return new SelectListItem() { Selected = (d.ToString() == "Manager"),  Text = d, Value = d }; }),
    null, new { @class = "custom-select" })

但是如果 ddlData 作为参数传递给视图并且视图模型定义为 @model IList<string> 下面的行也将正确填充 DropDownList

@Html.DropDownListFor(m => Model.GetEnumerator().Current,
    Model.Select(d =>
    {
        return new SelectListItem() { Selected = (d.ToString() == "Manager"), Text = d, Value = d };
    }),
    null, new { @class = "custom-select" })