在ASP.NET MVC 2中,我想写一个非常简单的下拉列表,它给出了静态选项。例如,我想提供“红色”,“蓝色”和“绿色”之间的选择。
见this MSDN article和example usage here on 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
)
)
%>
或者你不能写任何类,把这样的东西直接放到视图中。
从模型中的词典开始,避免大量的指法
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"))
您好,我是如何在一个项目中做到的:
@Html.DropDownListFor(model => model.MyOption,
new List<SelectListItem> {
new SelectListItem { Value = "0" , Text = "Option A" },
new SelectListItem { Value = "1" , Text = "Option B" },
new SelectListItem { Value = "2" , Text = "Option C" }
},
new { @class="myselect"})
我希望它可以帮助某人。谢谢
或者,如果它来自数据库上下文,您可以使用
@Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
用“请选择一个项目”
@Html.DropDownListFor(model => model.ContentManagement_Send_Section,
new List<SelectListItem> { new SelectListItem { Value = "0", Text = "Plese Select one Item" } }
.Concat(db.NameOfPaperSections.Select(x => new SelectListItem { Text = x.NameOfPaperSection, Value = x.PaperSectionID.ToString() })),
new { @class = "myselect" })
源自代码:Master Programmer && Joel Wahlund; 国王参考:https://stackoverflow.com/a/1528193/1395101 JaredPar;
感谢Master Programmer && Joel Wahlund && JaredPar;
祝你好运的朋友。
@using (Html.BeginForm()) {
<p>Do you like pizza?
@Html.DropDownListFor(x => x.likesPizza, new[] {
new SelectListItem() {Text = "Yes", Value = bool.TrueString},
new SelectListItem() {Text = "No", Value = bool.FalseString}
}, "Choose an option")
</p>
<input type = "submit" value = "Submit my answer" />
}
我认为这个答案类似于Berat,因为你将DropDownList的所有代码直接放在视图中。但我认为这是创建y / n(布尔)下拉列表的有效方法,所以我想分享它。
初学者的一些注意事项:
希望这有助于某人,