MVC3将字典值传递给dropdownlist并将关联的键绑定到模型

时间:2012-12-27 23:32:36

标签: c# asp.net-mvc asp.net-mvc-3

我正在尝试创建一个mvc3 c#webapplication。我正在尝试做的是创建一个DropDownlist并将字典传递给它。 Web界面中的用户应该看到字典的值并且有效。但我不想将选定的值绑定到模型,而是我想要关联的密钥。这有可能吗?

在该示例中,您将看到我如何将所选值绑定到模型:

@Html.DropDownListFor(model => model.EditDate, new SelectList(Versions.Values), Model.EditDate)

Versions.Values是DateTimes(字典的值)。在提交时,所选值将绑定到model.EditDate。但我想绑定所选值的关联键(值为id)。

我该怎么做?

提前致谢

1 个答案:

答案 0 :(得分:4)

您需要将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.EditDateint,因为您现在正在将字典的Keys设为下拉列表的Value。)