Reputation:
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);
}
Upvotes: 2
Views: 2550
Reputation:
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
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 selectedSelectList
from the
first one inside the ListBoxFor()
method (property DropDownItems
is already IEumerable<SelectListItem>
)Upvotes: 3