How does a multiple select list work with model binding in ASP.NET MVC?

Htmlasp.net MvcModel Binding

Html Problem Overview


If you have a select list set to multiple in ASP.NET MVC, how does the modelbinding work?

What does it return for your selected items, an array?

<SELECT NAME="toppings" MULTIPLE SIZE=5>
    <option value="mushrooms">mushrooms</option>
    <option value="greenpeppers">green peppers</option>
    <option value="onions">onions</option>
    <option value="tomatoes">tomatoes</option>
    <option value="olives">olives</option>
</SELECT>

Html Solutions


Solution 1 - Html

Yes, by default a multiselectlist will post through an array of the selected values.

This article has further information, including how to use strongly-typed views with a multiselectlist.

From the linked "article":

  • Your model or view model class needs a collection property for the IDs for the selected option items, e.g. List<int> ToppingIds.

  • In the controller action method to which the form containing your multi-select-list POSTs, you can access the selected option items thru the collection property you added to the model or view model class.

Solution 2 - Html

Yes, it returns an array.

View model:

public class MyViewModel
{
    public int[] SelectedIds { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

Controller:

public ActionResult Index()
{
    var model = new MyViewModel
    {
        // fetch the items from some data source
        Items = Enumerable.Select(x => new SelectListItem
        {
            Value = x.Id,
            Text = "item " + x.Id
        })
    };
    return View(model);
}

View:

@model MyViewModel
@Html.ListBoxFor(x => x.SelectedIds, Model.Items)

Solution 3 - Html

In VegTableViewmodel:

public IEnumerable<MultiSelectList> Vegetables { get; set; }

In the Controller: Get vegetables list, and then pass it to the VegTableViewModel's Vegetables property.

viewmodel.Vegetables = vegetables .Select(d => new MultiSelectList(d.VegName));

In the View:

@Html.ListBoxFor(m => m.L, new MultiSelectList(Model.Vegetables.Select(d => d.Items))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimpaticoView Question on Stackoverflow
Solution 1 - HtmlSam WesselView Answer on Stackoverflow
Solution 2 - HtmlHbasView Answer on Stackoverflow
Solution 3 - HtmlSreenath PlakkatView Answer on Stackoverflow