2012-04-10 78 views
1

我正在学习MVC3,我希望我的下拉列表使用colors作为数据。我该怎么做?如何使用此代码执行@ Html.DropDownListFor?

我知道我可以用@Html.DropDownList("colors")做到这一点,但我想知道如何用@Html.DropDownListFor(....)做到这一点?我有点难住,任何帮助和解释,将不胜感激。

为了方便起见,我把它放在一个页面中,所以这里不是真实世界的应用程序。

@functions { 

    private class Colors 
    { 
     public int ColorsId { get; set; } 
     public string ColorsName { get; set; } 
    } 

} 

@{ 
    var list = new List<Colors>() 
       { 
        new Colors() {ColorsId = 1, ColorsName = "Red"}, 
        new Colors() {ColorsId = 2, ColorsName = "Blue"}, 
        new Colors() {ColorsId = 3, ColorsName = "White"} 
       }; 
    var colors = new SelectList(list, "ColorsId", "ColorsName", 3); 
} 

@Html.DropDownListFor(???) 
+1

检查我的回答这个线程。它应该非常相似。 http://stackoverflow.com/questions/5097290/html-listboxfor-error-problem-asp-mvc-3/5176057#5176057 – 2012-04-10 12:30:19

+0

@AllenWang谢谢。绝对是一个很好的答案。提出了一个。 – 2012-04-10 17:15:48

回答

2
@Html.DropDownListFor(model => colors, colors) 
+0

谢谢。这个工作 – 2012-04-10 06:38:09

+0

你能帮我理解'model => colors'中的lambda表达式吗? – 2012-04-10 06:38:54

+0

该模型是标识包含要显示的属性的对象的表达式,并且我们返回用于填充下拉列表的SelectListItems的集合 – ionden 2012-04-10 06:41:58

1

您需要在页面顶部定义模型类型。使用lambda表达式指定模型的哪个属性绑定到下拉菜单。

@model MyModel 

@functions { 

    private class Colors 
    { 
     public int ColorsId { get; set; } 
     public string ColorsName { get; set; } 
    } 

} 

@{ 
    var list = new List<Colors>() 
       { 
        new Colors() {ColorsId = 1, ColorsName = "Red"}, 
        new Colors() {ColorsId = 2, ColorsName = "Blue"}, 
        new Colors() {ColorsId = 3, ColorsName = "White"} 
       }; 
    var colors = new SelectList(list, "ColorsId", "ColorsName", 3); 
} 

@Html.DropDownListFor(model => model.colors, colors) 
+0

你能帮我理解'model => model.colors'中的lambda表达式吗? – 2012-04-10 06:39:14

+0

它告诉'DropDownListFor'绑定到你模型类的'colors'属性。 – Eranga 2012-04-10 06:42:57

+0

你怎么知道它看起来ViewPage的Model属性? (我是一个C#初学者) – 2012-04-10 06:52:50

0
<%= Html.DropDownListFor(x => x.ColorsId, new SelectList(list, "ColorsId", "ColorsName")) %> 
+0

这并没有工作 – 2012-04-10 06:39:27

+0

对不起没有正确阅读它colors.typo的颜色,而不是列表 – 2012-04-10 06:45:11