How do you properly create a MultiSelect <select> using the DropdownList helper?

╄→尐↘猪︶ㄣ 提交于 2019-11-27 19:20:50

You don't use DropDownListFor if you want to create a multiselect list. You use the ListBoxFor helper.

View model:

public class MyViewModel
{
    public string[] SelectedIds { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

Controller:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        // preselect the first and the third item given their ids
        SelectedIds = new[] { "1", "3" }, 

        // fetch the items from some data source
        Items = Enumerable.Range(1, 5).Select(x => new SelectListItem
        {
            Value = x.ToString(),
            Text = "item " + x
        })
    };
    return View(model);
}

View:

@model MyViewModel
@Html.ListBoxFor(x => x.SelectedIds, Model.Items)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!