SelectedValues not working in MultiSelectList mvc

2019-03-25 03:36发布

问题:

I have a class like

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

In the controller I Fill MiltiselectItems and set selectedValues for it

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

In View Code I have

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

when run my action SelectedValues aren't working. What I'm doing wrong ?

回答1:

The last parameter of the MultiSelectList constructor takes an array of selected Id's not a collection of Category complex types.

If you change it to this instead it will work as expected:

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

It simply projects it into an array of Id's instead.

See below screen shot:

Ps I also had to add this to the constructor of Category to initialize the collection:

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