[英]Convert Table to 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中的下拉列表。
提前致谢
如果要通过按键订购Dictionary
为什么要使用Dictionary
? 您可以使用List
和Insert
:
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);
似乎您使事情变得过于复杂。 看起来可能会好一点:
model.State = resultSet.Tables[0]
.OrderBy(x => x.Id)
.Select(x => new SelectListItem()
{
Text = x.Id,
Value = x.StateName
}
).ToList();
只需将Id
和StateName
替换为您选择的适当列名即可(使用row.Field<int>(0)
和row.Field<int>(1)
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.