MVC SelectList vs MultiSelectList

4.1k Views Asked by At

In MVC, SelectList derives from MultiSelectList. I can't tell a difference between them though. For both, I have to tell it to select multiple items (I expected to not have to do this since the name has "multi" in it).

If you substitute "SelectList" with "MultiSelectList" in the code below, it will generate the same HTML:

<% 
var leftSelectList = new SelectList(Model.LeftSide,"Key","Value");
var attrs = new SortedDictionary<string, object> {{"class", "ui-widget"}};
MvcHtmlString disabledStyle = MvcHtmlString.Create(Html.Encode("'width:50px;'"));
attrs.Add("style", disabledStyle);
attrs.Add("multiple", "multiple");
attrs.Add("size", "5"); /*-- how many items to show--*/        
var leftItems =  Html.DropDownList("ddlLeftItems", leftSelectList, attrs); %>

<%= leftItems.ToHtmlString()%>

The generated HTML is:

<select class="ui-widget" id="ddlLeftItems" multiple="multiple" name="ddlLeftItems" size="5" style="&amp;#39;width:50px;&amp;#39;">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
  <option value="5">E</option>
  <option value="9">I</option>
</select>

So, which one should I use? Thank you.

2

There are 2 best solutions below

0
On

MultiSelectList is used with Html.ListBox and Html.ListBoxFor methods. These helpers generate this: HTML select multiple Attribute

0
On

The SelectList object doesn't generate HTML. It creates a list of items that can then be used elsewhere. The DropDownList helper function is what generates the HTML used on the page, which is why you see the exact same HTML.

The SelectList object is derived from MultiSelectList, but provides you with a property to get the single selected value (called SelectedValue). The MultiSelectList just has a property called SelectedValues that holds all selected values.

So if you are doing a multi-select list, then it doesn't really matter which one you use, but if you are doing a single-select list, then you should use SelectList because it makes it easier to get the selected value.