ListBoxFor not letting me select multiple items MVC

后端 未结 1 1431
感动是毒
感动是毒 2020-12-19 23:36

When I run the code, I can only select one item at a time, that\'s weird because \'ListBoxFor()\' is used to select multiple items, so what i want is:

Select multipl

相关标签:
1条回答
  • 2020-12-20 00:28

    You cannot bind a <select multiple> to a collection of complex objects (which is what List<SelectListItem> is). A <select multiple> posts back an array of simple values (in your case, if you select the 1st and 3rd options, it will submit [1, 3] (the values of the selected options).

    Your model needs a IEnumerable<int> property to bind to.

    public class ModelVariables
    {
        public IEnumerable<int> SelectedItems { get; set; }
        public IEnumerable<SelectListItem> DropDownItems { get; set; }
    }
    

    and then in the GET method

    public ActionResult Index()
    {
        var ModelVariables= new ModelVariables()
        {
            DropDownItems = Repository.DDFetchItems(),
            SelectedItems = new List<int>(){ 1, 3 } // to preselect the 1st and 3rd options
        };
        return View(model);
    }
    

    and in the view

    @Html.ListBoxFor(m => m.SelectedItems, Model.DropDownItems)
    

    Side notes

    1. Remove Selected = true in the DDFetchItems() method - its ignored by the ListBoxFor() method because its the value of the property your binding to which determines what is selected
    2. There is not need to build a new identical SelectList from the first one inside the ListBoxFor() method (property DropDownItems is already IEumerable<SelectListItem>)
    0 讨论(0)
提交回复
热议问题