3

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?

Dan88
  • 51
  • 2
  • 9
  • Possible duplicate of [Support for optgroup in dropdownlist .NET MVC?](http://stackoverflow.com/questions/607188/support-for-optgroup-in-dropdownlist-net-mvc) – Sherif Ahmed Feb 01 '17 at 16:25
  • Refer Option 1 of [this answer](http://stackoverflow.com/questions/37407811/mvc5-razor-html-dropdownlistfor-set-selected-when-value-is-in-array/37411482#37411482) using an `EditorTemplate` –  Feb 01 '17 at 21:48

1 Answers1

1

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.

Dan88
  • 51
  • 2
  • 9