How can a multi-select-list be edited using asp.net mvc?

Anders Juul picture Anders Juul · Jun 15, 2009 · Viewed 16k times · Source

I'd like to edit an object like the one below. I'd like the UsersSelectedList populated with one or more Users from the UsersGrossList.

Using the standard edit-views in mvc, I get only strings and booleans (not shown below) mapped. Many of the examples I find on google utilizes early releases of the mvc framework whereas I use the official 1.0 release.

Any examples of the view is appreciated.

public class NewResultsState
{
    public IList<User> UsersGrossList { get; set; }
    public IList<User> UsersSelectedList { get; set; }
}

Answer

eu-ge-ne picture eu-ge-ne · Jun 15, 2009

Assuming that User model has Id and Name properties:

<%= Html.ListBox("users", Model.UsersGrossList.Select(
    x => new SelectListItem {
        Text = x.Name,
        Value = x.Id,
        Selected = Model.UsersSelectedList.Any(y => y.Id == x.Id)
    }
) %>

Or with View Model

public class ViewModel {
    public Model YourModel;
    public IEnumerable<SelectListItem> Users;
}

Controller:

var usersGrossList = ...
var model = ...

var viewModel = new ViewModel {
    YourModel = model;
    Users = usersGrossList.Select(
        x => new SelectListItem {
            Text = x.Name,
            Value = x.Id,
            Selected = model.UsersSelectedList.Any(y => y.Id == x.Id)
        }
    }

View:

<%= Html.ListBox("users", Model.Users ) %>