我手上有两个字符串数组
`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 Fiddle