[英]MVC3 passing dictionary values to dropdownlist and binding associated key to the model
我正在嘗試創建一個mvc3 c#webapplication。 我正在嘗試做的是創建一個DropDownlist並將字典傳遞給它。 Web界面中的用戶應該看到字典的值並且有效。 但我不想將選定的值綁定到模型,而是我想要關聯的密鑰。 這有可能嗎?
在該示例中,您將看到我如何將所選值綁定到模型:
@Html.DropDownListFor(model => model.EditDate, new SelectList(Versions.Values), Model.EditDate)
Versions.Values是DateTimes(字典的值)。 在提交時,所選值將綁定到model.EditDate。 但我想綁定所選值的關聯鍵(值為id)。
我怎樣才能做到這一點?
提前致謝
您需要將Dictionary<T1,T2>
轉換為SelectList
,通常使用其中一個Linq
擴展。 所以,如果你有:
Dictionary<Int32,DateTime> Versions = new Dictionary<Int32,DateTime> {
{ 1, new DateTime(2012, 12, 1) },
{ 2, new DateTime(2013, 1, 1) },
{ 3, new DateTime(2013, 2, 1) },
};
然后你可以使用:
@Html.DropDownListFor(model => model.EditDate,
Versions.Select(x => new SelectListItem {
Text = x.Value.ToShortDateString(),
Value = x.Key.ToString(),
Selected = x.Value == Model.EditDate
})
)
(假設model.EditDate
是一個int
因為你現在正在使字典的Keys
成為下拉列表的Value
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.