Andrew Peterson
Andrew Peterson

Reputation: 56

Multiple default selected items in Listbox

I'm looking into creating an Edit page for a Company object that has multiple categories (that are predefined in a list). I have the list being sent through the ViewBag, and have the categories that the user selected in the Create page in an Array thanks to a ViewModel.

I can't figure out a way to have the ListBox prepopulate with the multiple values in my array. I was playing around with jQuery and was able to get one of the values to be selected, but when I try more than one nothing shows up. Any ideas?

@Html.ListBox("Category", new SelectList(ViewBag.Category, "Text", "Value"))

Upvotes: 1

Views: 1796

Answers (1)

David
David

Reputation: 218808

The SelectListItem object has a Selected property to indicate this. So I guess it would come down to how you build the SelectList. Currently you do this:

new SelectList(ViewBag.Category, "Text", "Value")

Which works, but gives you no control over the individual SelectListItems. Instead of building a SelectList, you can build an IEnumerable<SelectListItem> using the same method overload. Initially that might look like this:

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value
});

At this point you have more control over the individual items. Now it's just a matter of determining which ones should be selected. How do you determine that? Is it a property on the Category object? Something like this?:

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value,
    Selected = c.Selected
});

Or perhaps some other condition?:

ViewBag.Category.Select(c => new SelectListItem
{
    Text = c.Text,
    Value = c.Value,
    Selected = c.SomeValue == SomeCondition
});

How you determine that is up to you, and ideally something you can logically add to the backing model being used here.

Upvotes: 2

Related Questions