2009-06-15 42 views
12

我想编辑下面的对象。我想用UsersSelectedList填充来自UsersGrossList的一个或多个用户。如何使用asp.net mvc编辑多选列表?

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

欣赏任何视图的例子。

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

回答

6

使用Html.ListBox结合的IEnumerable SelectListItem

查看

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

     <input type="submit" value="submit" name="subform" /> 
     <% }%> 

控制器/型号:

 public List<CategoryInfo> GetCategoryList() 
    { 
     List<CategoryInfo> categories = new List<CategoryInfo>(); 
     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<SelectListItem> CategoryList { get; set; } 
     public IEnumerable<string> CategoriesSelected { get; set; } 

    } 
    public ActionResult Category(ProductViewModel model) 
    { 
     IEnumerable<SelectListItem> 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); 
    } 
8

假设用户模型有编号和名称属性:

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

或者与视图模型

public class ViewModel { 
    public Model YourModel; 
    public IEnumerable<SelectListItem> 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) %> 
1

@ EU-GE-NE <三江源这么多你的答案 - 是有真正的无法找到一种方法来多选一个从模型到模型的值列表。 使用您的代码我在编辑/更新页面中使用了ListBoxFor Html控件,并在保存时将整个模型传回给我的控制器(包括多选的值)。

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

)%>