【问题标题】:How to do a @Html.DropDownListFor with this code?如何使用此代码执行@Html.DropDownListFor?
【发布时间】:2012-04-10 14:44:09
【问题描述】:

我正在学习 MVC3,我希望我的下拉列表使用 colors 作为此处的数据。我该怎么做?

我知道我可以用@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( ??? )

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-3 razor drop-down-menu


【解决方案1】:
@Html.DropDownListFor(model => colors, colors)

【讨论】:

  • 你能帮我理解model =&gt; colors这里的lambda表达式吗?
  • 模型是标识包含要显示的属性的对象的表达式,我们返回用于填充下拉列表的 SelectListItems 集合
  • 通常我将 lambdas 视为 x => x.something;有趣的是,它不是模型 => model.colors。你能向我解释一下为什么吗? (这里是 c# 初学者)
  • 如果您使用了 model.colors,编译器会抱怨这是一个动态表达式,并且不受支持,所以我只返回了颜色,它就可以工作了。如果你还看这个方法的第一个参数是 Expression> 所以返回的值不应该是动态值
  • 啊。感谢那。不过我想知道。我知道 lamda = "goes to" 但在这里,"model" 去哪里了?我从来没有见过没有像这样使用左侧参数的情况下使用 lambda。介意你能帮助我理解为什么可以编写这样的代码吗?我认为它看起来像是某种“黑客”……只是为了实现功能
【解决方案2】:

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

@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)

【讨论】:

  • 你能帮我理解model =&gt; model.colors这里的lambda表达式吗?
  • 它告诉DropDownListFor 绑定到模型类的colors 属性。
  • 你怎么知道它查看了 ViewPage 的 Model 属性? (我是 C# 初学者)
  • @JanCarloViray 因为DropDownListFor 方法可以检查您提供的 lambda 表达式以构建呈现&lt;select&gt; 标记所需的元数据。您可以通过 MVC 源代码查看它是如何完成的。
【解决方案3】:
<%= Html.DropDownListFor(x => x.ColorsId, new SelectList(list, "ColorsId", "ColorsName")) %> 

【讨论】:

  • 抱歉没有正确阅读。颜色错字而不是列表
猜你喜欢
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-12
  • 2015-07-12
  • 1970-01-01
  • 2014-02-17
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多