tags:

views:

369

answers:

2

Hello

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

A: 

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?

shanabus
Is there some easy trick in visual studio to do that?
molgan
I'm not sure, I don't think so. You could use a foreach() loop and just print them to the Console.
shanabus
+1  A: 

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();
dahlbyk
damn .. you beat me by 14 seconds :)
sirrocco