简体   繁体   中英

Set multiple values as selected for "Html.DropDownListFor"

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM