22

I'm trying to set multiple values in a select list:

SelectList List = new SelectList(MyListItems, "valField", "dataField", <selected values>);

What object/values do I use for to select multiple items?

3 Answers 3

32

You want to use MultiSelectList instead which has a constructor to meet your needs:

public MultiSelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField,
    IEnumerable selectedValues
)
Sign up to request clarification or add additional context in comments.

5 Comments

okay...will that work with @Html.DropDownList() in my razor code?
no, you'll have to use Html.ListBox... native HTML dropdown lists don't support multi-select. See blog.garypretty.co.uk/index.php/2010/02/26/…
@RobertLevy you can use the DropDownList like this: @Html.DropDownList("yourName", yourMultiSelectList, new { multiple = "" })
@Matus I know I'm "coming from the future" now, but it's better to stick to Html.ListBox / Html.ListBoxFor since Razor, for some reason, doesn't "remember" the previously selected options properly when using DropDownList or DropDownListFor with a MultiSelectList.
Perfect was looking for the MultiSelect Option for 2 days now
20

Example:

class Person
{
    int Id{ get; set; }
    string Name { get; set; }
}

...

var people = new List<Person>()
{
    new Person{ Id = 1, Name = "Steve" },
    new Person{ Id = 2, Name = "Bill" },
    new Person{ Id = 3, Name = "John" },
    new Person{ Id = 4, Name = "Larry" }
}
SelectList List = new MultiSelectList(people, "Id", "Name", new[]{ 2, 3 });

Comments

2

Use the The Harvest Chosen jQuery plugin. See my tutorial Working with the DropDownList Box and jQuery which shows how to do this.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.