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 ?
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>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With