Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

c# - ListBoxFor not letting me select multiple items MVC

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 multiple items

View (Index.cshtml):

<div>
    @Html.ListBoxFor(m => m.DropDownItems, new MultiSelectList(Repository.DDFetchItems(), "Value", "Text", Model.DropDownItems))
</div>

Model (ModelVariables.cs):

public class ModelVariables
{
    public List<SelectListItem> DropDownItems { get; set; } 
}

public static class Repository
{
    public static List<SelectListItem> DDFetchItems()
    {
        return new List<SelectListItem>()
        {
            new SelectListItem(){  Text = "Dogs", Value = "1", Selected = true},
            new SelectListItem(){  Text = "Cats", Value = "2"},
            new SelectListItem(){  Text = "Death", Value = "3"}
        };
    }
}

Controller (HomeController.cs):

[HttpGet]
public ActionResult Index()
{
    ModelVariables model = new ModelVariables()
    {
        DropDownItems = Repository.DDFetchItems()  
    };
    return View(model);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...