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

前端 未结 3 376
时光取名叫无心
时光取名叫无心 2021-02-02 01:00

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 i

3条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 01:52

    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 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 ) %>
    

提交回复
热议问题