2014-02-17 50 views
12

我有一個像SelectedValues在MultiSelectList不工作​​MVC

public class Category 
    { 
     public int ID { get; set; } 
     public string Name { get; set; } 
     public ICollection<Category> CategorySelected { get; set; } 
     public static List<Category> GetOptions() 
     { 
      var categories = new List<Category>(); 
      categories.Add(new Category() { ID = 1, Name = "Bikes" }); 
      categories.Add(new Category() { ID = 2, Name = "Cars" }); 
      categories.Add(new Category() { ID = 3, Name = "Trucks" }); 

      return categories; 
     } 
    } 

在控制器I類填充MiltiselectItems和設置selectedValues它

public ActionResult Index() 
    { 
     Category cat=new Category(); 
     cat.CategorySelected.Add(new Category { ID =1, Name = "Bikes" }); 
     cat.CategorySelected.Add(new Category { ID =3, Name = "Trucks" }); 

     var list = Category.GetOptions(); 
     product.Categories = new MultiSelectList(list, "ID", "Name", CategorySelected); 
    } 

在查看代碼我有

@Html.ListBox("Category", Model.Categories) 

運行我的操作時SelectedValues不起作用。我做錯了什麼?

回答

10

構造函數MultiSelectList的最後一個參數需要一個選定的Id不是Category複雜類型的集合。

如果改成這樣反而會按預期工作:

product.Categories = new MultiSelectList(list, "ID", "Name", cat.CategorySelected.Select(c => c.ID).ToArray()); 

它只是其投影到的Id的,而不是一個數組。

請參見下面的屏幕截圖:

Screen grab

詩我也不得不把它添加到Category構造函數初始化集合:

public Category() 
{ 
    CategorySelected = new List<Category>(); 
}