-
萧十郎
请参阅此MSDN文章以及Stack Overflow上的示例用法。假设您有以下Linq / POCO课程:public class Color{
public int ColorId { get; set; }
public string Name { get; set; }}让我们说你有以下模型:public class PageModel {
public int MyColorId { get; set; }}最后,让我们说你有以下颜色列表。它们可以来自Linq查询,来自静态列表等:public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}};在您的视图中,您可以创建一个下拉列表,如下所示:<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
-
哆啦的时光机
<%:
Html.DropDownListFor(
model => model.Color,
new SelectList(
new List<Object>{
new { value = 0 , text = "Red" },
new { value = 1 , text = "Blue" },
new { value = 2 , text = "Green"}
},
"value",
"text",
Model.Color
)
)%>或者你不能写任何类,把这样的东西直接放到视图中。
-
慕田峪4524236
从模型中的词典开始,避免大量的指法namespace EzPL8.Models{
public class MyEggs
{
public Dictionary<int, string> Egg { get; set; }
public MyEggs()
{
Egg = new Dictionary<int, string>()
{
{ 0, "No Preference"},
{ 1, "I hate eggs"},
{ 2, "Over Easy"},
{ 3, "Sunny Side Up"},
{ 4, "Scrambled"},
{ 5, "Hard Boiled"},
{ 6, "Eggs Benedict"}
};
}
}在视图中将其转换为列表以供显示@Html.DropDownListFor(m => m.Egg.Keys,
new SelectList(
Model.Egg,
"Key",
"Value"))