2
votes

I have an MVC View page with an Html.DropDownListFor within an array. In the code behind I create a 'SelectListItem' List which is a dynamic list populated from the database.

Originally the way I built it the selected Item in the DDL was never set, it always defaulted to the first value. I looked up the problem and I found out you needed to pass the selected value like this

Html.DropDownListFor(x => x.Sections[i].item, new SelectList(Model.DDL, "Value", "Text", Model.Sections[i].item), new { @class = "form-control" })

Since then I have added a 'SelectListGroup' to group the Drop Down List items with the 'OptGroup' tag.

The issue I have is I cant get the 'DropDownListFor' to work with the Grouping using the method I used above. It does work perfectly if I use

Html.DropDownListFor(x => x.Sections[i].Item, Model.DDL, htmlAttributes: new { @class = "form-control" })

Unfortunately I then have the issue of the Current selected value not being set.

How can I get the 'OptGroup' working and have the selected item set witin an array?

1
Refer Option 1 of this answer using an EditorTemplateuser3559349

1 Answers

1
votes

I eventually found the answer...

This is the code in the view I used in the end

@Html.DropDownListFor(m => m.Sections[i].Item, Model.DDL.Select(x => new SelectListItem() { Value = x.Value, Text = x.Text, Group = x.Group, Selected = (x.Value == Model.Sections[i].Item) }).ToList())

I can now have the OptGroup working with the Selected item set.