Answers:
请参阅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
)
)
%>
或者您可以不编写任何类,直接将类似这样的内容放入视图中。
通过在模型中使用字典来避免过多的繁琐指法
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 ;
谢谢首席程序员 && 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" />
}
我认为这个答案与培拉特的答案相似,因为您将DropDownList的所有代码直接放在视图中。但是我认为这是创建ay / n(布尔值)下拉列表的有效方法,因此我想与他人分享。
初学者注意事项:
希望这对某人有帮助,