我需要填充下拉從數據庫表鍵和值。我正在做的是表格轉換成的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中的下拉列表。
由於提前
P.S.,字典是沒有順序的,所以你從'sortedStates'字典拿到訂單不出來,你期望的那樣。 – 2014-10-09 15:36:37