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

后端 未结 1 1931
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 23:23

(sorry, there are several item here but none seems to allow me to get this working.)

I want to create a DropDownList which allows multiple selection. I am able to po

相关标签:
1条回答
  • 2020-12-02 23:43

    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)
    
    0 讨论(0)
提交回复
热议问题