How To Handle Multiple Select Lists In ASP NET MVC


RSS Feed

<< January | February | March >>

Sunday, 21st February 2010

I recently wrote a jQuery plugin for multiple select lists. This is because I was creating a two-sided multi-select in an ASP.NET MVC application.

I thought it would be useful for people if I posted how I've handled the binding of the multi-select list in the ASP.NET MVC application as it is just slightly trickier than binding a normal drop-down list.

I have updated this example to show that you ought to create the MultiSelectList on the view as it is specific to the presentation - the view could decide to turn the Store" list in any way it likes and coding the model to contain a SelectList or MultiSelectList would result in tying the view to displaying a drop down.

Add an IEnumerable<string> property to your model to hold the selected values and pass in your list of items that can be selected:

public IEnumerable<string> SelectedStuff { get; set; }
public IEnumerable<Store> Stores { get; set; }

And in your controller, set the list of Stores so you can use them in the view.

model.Stores = GetStores();

And finally, in your view, you convert the IEnumerable<Store> list into a MultiSelectList, passing in Model.SelectedStuff, which sets the selected items if you have any.

<%= Html.ListBox("SelectedStuff",new MultiSelectList(Model.Stores, "Value", "Text", Model.SelectedStuff);, new { size = "8" }) %>

You Are Here: Home » Blog » How To Handle Multiple Select Lists In ASP NET MVC