簡體   English   中英

為“Html.DropDownListFor”設置多個值

[英]Set multiple values as selected for "Html.DropDownListFor"

我手頭有兩個字符串數組

`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.

如何使用Html.DropDownListFor來顯示這種情況? 我嘗試過這樣的事情

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

但是給出了一個錯誤

運算符'=='不能應用於'string'和'string[]類型的操作數

誰能指出解決這個問題的正確方法。

由於Model.Country是一個列表/數組,所以不應該使用==而是使用.Contains()來檢查列表/數組中的值是否。

對於多選,建議使用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 = "" })

.NET 小提琴示例

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM