C#字典键到数组

时间:2018-05-25 15:15:07

标签: c# asp.net arrays dictionary

我有一个下拉列表,可以让我选择多个项目。我正在使用字典列表来显示项目。因此,为了选择多个项目,我需要将字典列表转换为数组。这是它的样子:

public static Dictionary<string, string> DropdownItem = new Dictionary<string, string>()
    {
        { "", "" },
        { "1", "item1" },
        { "2", "item2" },
        { "3", "item3" },
        { "4", "item4" },
        { "5", "item5" },
    };

       <div class="form-group">
            <label asp-for="DropdownItem" class="control-label" multiple></label>
            <span asp-validation-for="DropdownItem" class="text-danger"></span>
            <select asp-for="DropdownItem" class="form-control">
                <option value="" disabled="disabled" selected="selected">drop down</option>
                <option value="1">item1</option>
                <option value="2">item2</option>
                <option value="3">item3</option>
                <option value="4">item4</option>
                <option value="5">item5</option>
            </select>
        </div>

这就是我将其转换为数组时的样子:

public static Dictionary<string, string[]> DropdownItem = new Dictionary<string, string[]>()
    {
        { "", "" },
        { "1", "item1" },
        { "2", "item2" },
        { "3", "item3" },
        { "4", "item4" },
        { "5", "item5" },
    };

这是对的吗?

1 个答案:

答案 0 :(得分:1)

看起来你正在使用Tag Helpers所以你应该能够做到:

/*
    This assumes that you have your Dictionary<string, string> DropdownItem 
    in your @model 
*/
<select asp-for="DropdownItem" 
        asp-items="@(new SelectList(Model.DropdownItem,"Value","Key"))">
    <option>Please select one</option>
</select>

我们无需或无理由将您的Dictionary<string, string>变为Dictionary<string, string[]>