如何写一个简单的Html.DropDownListFor()? [英] How to write a simple Html.DropDownListFor()?

查看:465
本文介绍了如何写一个简单的Html.DropDownListFor()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET MVC 2,我想编写一个非常简单的下拉列表赋予静态的选项。比如我想提供红,蓝和绿之间的选择。

In ASP.NET MVC 2, I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".

推荐答案

请参见这个MSDN文章和<一个href=\"http://stackoverflow.com/questions/1916462/dropdownlistfor-in-editortemplate-not-selecting-value\">example这里使用堆栈溢出。

假设你有以下的LINQ / POCO类:

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

和我们说,你有以下型号:

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

最后,让我们说,你有颜色下面的列表。他们可能来自LINQ查询,从静态列表等。

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

在您看来,您可以创建一个下拉列表,像这样:

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

这篇关于如何写一个简单的Html.DropDownListFor()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆