ListBoxFor MultiSelectList does not select values

前端 未结 1 1616
天涯浪人
天涯浪人 2021-01-03 06:43

I\'m incredibly confused, because this seems like it should be simple but I can\'t get my ListBox to be populated with selected values. I\'ve looked at several

相关标签:
1条回答
  • 2021-01-03 07:24

    You cannot bind a <select> element to a collection of complex objects. A multiple select only posts back an array of simple values - the values of the selected options.

    Your model needs to be

    public class ItemViewModel
    {
        public IEnumerable<Item> AllItems { get; set; }
        public IEnumerable<int> SelectedItems { get; set; }
    }
    

    and in the controller

    SelectedItems = new List<int>(){ 1 }
    

    then using

    @Html.ListBoxFor(m => m.SelectedItems, new SelectList(Model.AllItems, "Id", "Name")
    

    will select the first option in the dropdownlist.

    Note that the ListBoxFor() method sets multiple="multiple" so there is no need to set it again. In addition, Setting the last parameter of in the SelectList() (or MultiSelectList()) constructor is pointless. Its the value of the property your binding to which determines what is selected and internally the ListBoxFor() method ignores that parameter.

    I would also suggest your property should be

    public IEnumerable<SelectListItem> AllItems { get; set; }
    

    so that you can simply use

    @Html.ListBoxFor(m => m.SelectedItems, Model.AllItems)
    
    0 讨论(0)
提交回复
热议问题