None
None

Reputation: 5670

Html.DropDownListFor value duplicates when add a Preselect value

My code is like this

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

Everything looks fine to me, But when Dropdown loads it loads with two "Manager" in it. I want only ddlData items to populate and preselect "Manager".

Upvotes: 1

Views: 121

Answers (1)

Victor
Victor

Reputation: 8925

If the ddlData is defined inside the view you could try:

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

But if the ddlData is passed to the view as a parameter and the view model defined as @model IList<string> the below line will populate teh DropDownList correctly too:

@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" })

Upvotes: 1

Related Questions