How does a multi-segment list work with model binding in ASP.NET MVC?

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

What does it return for selected elements, 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> 
+44
html asp.net-mvc model-binding
Aug 10 '09 at 15:16
source share
3 answers

Yes, by default, a multi-select list will send through an array of selected values.

This article provides additional information, including how to use strongly typed views in a multi-select list.

From the related "article":

  • For a model model or view model class, a collection property for identifiers for selected option elements, for example, is required. List<int> ToppingIds .
  • In the controller’s action method, which includes a form containing your POST requests with several lists, you can access the selected option elements through the collection property that you added to the model or class of the view model.
+22
Aug 10 '09 at 15:34
source share

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) 
+17
Jun 01 '13 at 18:19
source share

In VegTableViewmodel:

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

In the controller: Get a list of vegetables, and then pass it to the VegTableViewModel Vegetables property.

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

In view:

 @Html.ListBoxFor(m => mL, new MultiSelectList(Model.Vegetables.Select(d => d.Items)) 
+7
Nov 21 '11 at 11:41
source share



All Articles