Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SelectedValues not working in MultiSelectList mvc

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 ?

like image 439
M.Azad Avatar asked Feb 17 '14 10:02

M.Azad


1 Answers

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:

Screen grab

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

public Category()
{
   CategorySelected = new List<Category>();
}
like image 130
hutchonoid Avatar answered Oct 21 '22 21:10

hutchonoid