2014-10-09 90 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

相关问题