Posted by: Cirilo Meggiolaro | 04/30/2009

Tip of the day #198 – ASP.NET MVC – ListBox controls

Let’s check today how to add a ListBox control to your ASP.NET MVC views.

How to…

The object we are going to use to bind items to a ListBox is the System.Web.Mvc.MultiSelectList and the way how we will implement the ListBox control depends on how you are binding your view. The following constructors are available:

  • public MultiSelectList(IEnumerable items);
  • public MultiSelectList(IEnumerable items, IEnumerable selectedValues);
  • public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField);
  • public MultiSelectList(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues);

Not strongly-typed Views

If you are creating a View that is not strongly-typed, you have the option to send the MultiSelectList object via the ViewData dictionary and use it on the View to bind the content to a ListBox control. You have also the option to send an instance of an IEnumerable<T> to the View and create the MultiSelectList instance directly on the View.

Let’s start creating a method that builds a list of cities and retrieves an instance of a MultiSelectList object. The method accepts an array of strings as parameter that represents the selected values.

public class City
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public MultiSelectList GetCities(string[] selectedValues)
{
    List<City> cities = new List<City>()
    {
        new City() { ID = 1, Name= “Sao Paulo” },
        new City() { ID = 2, Name= “Toronto” },
        new City() { ID = 3, Name= “New York” },
        new City() { ID = 4, Name= “Vancouver” }
    };

    return new MultiSelectList(cities, “ID”, “Name”, selectedValues);
}

From the action method, let’s add the return of the GetCities method to the ViewData dictionary:

public ActionResult MultiSelection()
{
    ViewData[“citieslist”] = GetCities(null);
    return View();
}

Create a view by right-clicking the action method and selecting Add View or by pressing ctrl M, V. The following View markup contains a form, a ListBox that accesses the ViewData dictionary entry and convert it to MultiSelectList and a submit button.

<% using (Html.BeginForm()) {%>
<p>
<label for=”Cities”>Cities:</label>

<%= Html.ListBox(“Cities”, ViewData[“citieslist”] as MultiSelectList)%>
</p>
<p>
<input type=”submit” value=”Submit” />
</p>
<% } %>

Back to our controller class, let’s add the action method that will handle the posts when a user hits the submit button. We are going to access the form collection to get the selected values on the Cities control:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MultiSelection(FormCollection form)
{
    string selectedValues = form[“Cities”];
    ViewData[“citieslist”] = GetCities(selectedValues.Split(‘,’));
    return View();
}

Strongly-typed Views

When working with strongly-typed views you have to create your ViewModel first:

public class MyModelView
{
    public List<string> Cities { get; set; }
    public MultiSelectList CityList { get; private set; }

    public MyModelView()
    {
        this.CityList = GetCities(null);
    }

    public MultiSelectList GetCities(string[] selectedValues)
    {
        List<City> cities = new List<City>()
        {
            new City() { ID = 1, Name= “Sao Paulo” },
            new City() { ID = 2, Name= “Toronto” },
            new City() { ID = 3, Name= “New York” },
            new City() { ID = 4, Name= “Vancouver” }
        };

         return new MultiSelectList(cities, “ID”, “Name”, selectedValues);
    }
}

On the controller class, let’s create the action method responsible for request a View to be rendered:

public ActionResult City()
{
    return View(new MyModelView());
}

Create a strongly-typed view by right-clicking the action method and selecting Add View or by pressing ctrl M, V. When the Add View dialog is displayed, mark the “Create a strongly-typed view” and select the MyModelView from the View data class DropDownList and click OK. Let’s create a form and add a ListBox to it:

<% using (Html.BeginForm()) {%>
<p>
<label for=”Cities”>Cities:</label>

<%= Html.ListBox(“Cities”, Model.CityList) %>
</p>
<p>
<input type=”submit” value=”Submit” />
</p>
<% } %>

On the controller class let’s add the action method that will handle the post operation. Using the ModelView as parameter will make the selected items accessible via the Cities property. Only the values of each selected item is stored.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult City(MyModelView myModelView)
{
    // myModelView.Cities stores a list of the selected values.
    […]
    return View();
}

About these ads

Responses

  1. thx for article

  2. Thanks for the article. Can you tell me how to update the list box changes (which i have done thru javascript) to database while clicking submit button

  3. Many thanks for this code! This is the best code example I have yet found for managing the multiselect list within a form.

  4. Thanks mate, this is the only example that really works, life saver!

  5. but if user select more then one fields in the list how to catch the data in my controller

  6. this is great stuff, thanks for sharing with us.
    @lydia check out the following url it might be useful for you..

    http://www.mindstick.com/Articles/09ccfe6f-c6c1-43d4-a801-d2cadecc380b/?ListBox%20control%20in%20MVC

    Thanks !!!

  7. Great! Thank you!!!

  8. Where is “City” defined in the strongly typed example?

  9. Hi John,

    The City object is a simple data transfer object containing 2 properties: ID and Name. I have updated the post to reflect that.

    Thanks!

  10. Really great post and helped me a lot – was struggling this afternoon to remember how to use a listbox with MVC, 5 min read and all was clear!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: