2009-08-17 12 views
2

選択リストで選択項目を取得する際に問題があります。SelectlistItem selected = true problem

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

カテゴリ4つの項目を返し、選択された私は3つの項目が正しいである、そこにある「product.Categories」を合わせると.......すべての偽です....何とかそれはdoesntのtrueに設定されます。

何が問題なのでしょうか? /M

答えて

1

使用しているContains()のオーバーロードは、あなたがEquals()GetHashCode()を上書きしていない限りだけで、まったく同じインスタンスと一致しますデフォルトのオブジェクトの比較を、使用する予定です。 1つのオプションは、カスタムCategoryEqualityComparerを作成してthis overload of Contains()に渡すことです。それとも、あなただけの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(); 
+0

あなたは14秒で私を打つ:) – sirrocco

0

「allCategories」を_cr.GetCategoriesコレクションに設定していることがわかります。そのコレクションにカテゴリが含まれていることは確かですか? [カテゴリ]フィールドに商品カテゴリが含まれていないようです。あなたは各コレクションにあるものを投稿できますか?

+0

はそれを行うにはVisual Studioでいくつかの簡単なトリックはありますか? –

+0

私は確信していません、私はそうは思わない。 foreach()ループを使用して、コンソールに出力するだけで済みます。 – shanabus