如何使用asp.net mvc编辑多选列表?

我想编辑一个像下面那样的对象。 我想用UsersSelectedList填充UsersGrossList中的一个或多个用户。

使用mvc中的标准编辑视图,我只得到映射的字符串和布尔值(下面未显示)。 我在谷歌上找到的许多例子都使用了mvc框架的早期版本,而我使用的是官方的1.0版本。

任何观点的例子都表示赞赏。

public class NewResultsState { public IList UsersGrossList { get; set; } public IList UsersSelectedList { get; set; } } 

将Html.ListBox与IEnumerable SelectListItem结合使用

视图

  <% using (Html.BeginForm("Category", "Home", null, FormMethod.Post)) { %> <%= Html.ListBox("CategoriesSelected",Model.CategoryList )%>  <% }%> 

控制器/型号:

  public List GetCategoryList() { List categories = new List(); categories.Add( new CategoryInfo{ Name="Beverages", Key="Beverages"}); categories.Add( new CategoryInfo{ Name="Food", Key="Food"}); categories.Add(new CategoryInfo { Name = "Food1", Key = "Food1" }); categories.Add(new CategoryInfo { Name = "Food2", Key = "Food2" }); return categories; } public class ProductViewModel { public IEnumerable CategoryList { get; set; } public IEnumerable CategoriesSelected { get; set; } } public ActionResult Category(ProductViewModel model ) { IEnumerable categoryList = from category in GetCategoryList() select new SelectListItem { Text = category.Name, Value = category.Key, Selected = (category.Key.StartsWith("Food")) }; model.CategoryList = categoryList; return View(model); } 

假设User模型具有Id和Name属性:

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

或者使用View Model

 public class ViewModel { public Model YourModel; public IEnumerable Users; } 

控制器:

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

视图:

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

@ eu-ge-ne

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

)%>