Reputation: 295
I am trying to create a multiselect list and specify the default values for the dropdown, but the default values I am providing are being ignored.
My controller looks like this:
var ProvisionFromDb = (from Provision in db.Provisions
orderby Provision.Provision1 ascending
select new SelectListItem
{
//select all items
Selected = true,
Text = Provision.AltDescription,
Value = Provision.Provision1.ToString()
}).ToList();
ViewBag.ProvisionDropdown = new MultiSelectList(ProvisionFromDb, "Value", "Text");
In my view, I have the following statement:
@Html.ListBox("ProvisionId", (MultiSelectList)ViewBag.ProvisionDropdown)
Everything works, except for the default values not being selected. I assume this is because of MultiSelectList not recognizing the selected property in the SelectList objects. What is the simplest way to correct this?
Additional info: In the razor view statement, "ProvisionId" represents the name/ID of the select dropdown that is being created.
Upvotes: 2
Views: 1811
Reputation: 295
The solution here was to put the defaults into an overloaded MultiSelectList constructor, where the 4th parameter is an array representing values of the default selected items.
In my case, I did not need to define a model. The following worked:
ViewBag.ProvisionDropdown = new MultiSelectList(ProvisionFromDb, "Value", "Text", new[] {"Selected Value1","Selected Value2"});
A linq query could have also been used to generate this array based on the "Selected" property of SelectListItem.
Upvotes: 3
Reputation: 239430
The options rendered as selected are determined by the value of what you're binding to. Here, namely, "ProvisionId". If that's a property on your model, you should use ListBoxFor
instead and then set it to the list of Provision1
values you want to be selected. If it's not a property on your model, you can set something like ViewBag.ProvisionId
with that list.
Upvotes: 1