2014-10-09 92 views
0

我需要填充下拉從數據庫表鍵和值。我正在做的是表格轉換成的IEnumerable <SelectListItem>

 Dictionary<int, string> states = resultSet.Tables[0].AsEnumerable() 
          .ToDictionary(row => row.Field<int>(0), 
                 row => row.Field<string>(1)); 
     //Add the list item 
     states.Add(0, "Select State"); 
     //Sort the dictionary to set the "0" item at the top 
     var sortedStates = (from entry in states orderby entry.Key ascending select entry) 
        .ToDictionary(pair => pair.Key, pair => pair.Value); 

     //Form the SelectListItem 
     model.State = from s in sortedStates 
         select new SelectListItem() 
         { 
          Text = s.Value, 
          Value = s.Key.ToString(CultureInfo.InvariantCulture) 
         }; 

我得到正確的輸出,但我覺得它是更詳細闡述。有什麼最好的方法來填充MVC中的下拉列表。

由於提前

+0

P.S.,字典是沒有順序的,所以你從'sortedStates'字典拿到訂單不出來,你期望的那樣。 – 2014-10-09 15:36:37

回答

1

爲什麼你使用Dictionary如果你想通過密鑰來訂購吧?你可以使用一個ListInsert

List<SelectListItem> allItems = resultSet.Tables[0].AsEnumerable() 
    .OrderBy(r => r.Field<int>(0)) 
    .Select(r => new SelectListItem { Text = r.Field<string>(1), Value = r.Field<int>(0).ToString() }) 
    .ToList(); 

SelectListItem defItem = new SelectListItem { Text = "Select State", Value = "0" }; 
allItems.Insert(0, defItem); 
+0

Simple..straight前進。 – 2014-10-09 16:36:31

0

好像你過於複雜的事情。這看起來可能會好一點:

model.State = resultSet.Tables[0] 
    .OrderBy(x => x.Id) 
    .Select(x => new SelectListItem() 
     { 
      Text = x.Id, 
      Value = x.StateName 
     } 
    ).ToList(); 

只是與您(row.Field<int>(0)row.Field<int>(1))選擇適當的列名替換IdStateName

相關問題