Reputation: 9298
I'm having problems with getting selected items in a select-list.
Product product = _pr.GetProducts().ByProductID(productID).First();
product.Categories.Load();
ICollection<Category> allCategories = _cr.GetCategories().ToList();
List<SelectListItem> Categories = (from category in allCategories
select
new SelectListItem
{
Selected = product.Categories.Contains(category),
Value = category.CategoryID.ToString(),
Text = category.Categoryname
}).ToList();
Categories return 4 items, and selected is false on all....... If I hover "product.Categories" there are 3 items there, which is correct.... but somehow it doesnt get set to true.
What might be wrong? /M
Upvotes: 2
Views: 2760
Reputation: 77540
The overload of Contains()
that you're using is going to use the default object comparison, which will only match the exact same instance unless you've overridden Equals()
and GetHashCode()
. One option is to create a custom CategoryEqualityComparer
and pass it to this overload of Contains()
. Or, you could just join the categories on ID:
Product product = _pr.GetProducts().ByProductID(productID).First();
product.Categories.Load();
ICollection<Category> allCategories = _cr.GetCategories().ToList();
List<SelectListItem> Categories = (
from category in allCategories
join pc in product.Categories
on category.CategoryID equals pc.CategoryID into j
select
new SelectListItem
{
Selected = j.Any(),
Value = category.CategoryID.ToString(),
Text = category.Categoryname
}).ToList();
Upvotes: 1
Reputation: 13115
I see that you set 'allCategories' to a _cr.GetCategories collection - are you sure the product contains categories from that collection? It looks like your Categories field doesn't contain any of the product categories. Can you post what is in each collection?
Upvotes: 0