Set multiple values as selected for "Html.DropDownListFor"

41 Views Asked by At

I have two string arrays in hand

`mdm.Country` - Contains all the countries that needs to be displayed on the drop down.
`Model.Country` - Contains multiple selected items that needs to be marked as selected on the 
drop down.

How can I use Html.DropDownListFor to display this scenario? I have tried something like this

                                @Html.DropDownListFor(n => n.Country, mdm.Country.Select
(d => { return new SelectListItem() { Selected = (d.ToString() == Model.Country), Text = d, Value = d }; }), null, new { @class = "custom", @multiple = "" })

But gives an error

Operator '==' cannot be applied to operands of type 'string' and 'string[]

Can anyone please point out the correct way to address this.

1

There are 1 best solutions below

0
Yong Shun On

Since Model.Country is a list/array, should not use == but use .Contains() to check whether the value in the list/array.

For multiple select, would suggest using Html.ListBoxFor()

@Html.ListBoxFor(n => n.Country, 
                    mdm.Country
                    .Select(x => new SelectListItem
                    {
                        Selected = Model.Country.Contains(x),
                        Text = x,
                        Value = x
                    })
                    , 
                    new { @class = "custom", @multiple = "" })

Sample .NET Fiddle