Rin*_*sse 128 c# asp.net html.dropdownlistfor asp.net-mvc-2
在ASP.NET MVC 2中,我想写一个非常简单的下拉列表,它给出了静态选项.例如,我想提供"红色","蓝色"和"绿色"之间的选择.
Eva*_*gle 181
请参阅此MSDN文章以及Stack Overflow上的示例用法.
假设您有以下Linq/POCO课程:
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
让我们说你有以下模型:
public class PageModel
{
public int MyColorId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
最后,让我们说你有以下颜色列表.它们可以来自Linq查询,来自静态列表等:
public static IEnumerable<Color> Colors = new List<Color> {
new Color {
ColorId = 1,
Name = "Red"
},
new Color {
ColorId = 2,
Name = "Blue"
}
};
Run Code Online (Sandbox Code Playgroud)
在您的视图中,您可以创建一个下拉列表,如下所示:
<%= Html.DropDownListFor(n => n.MyColorId,
new SelectList(Colors, "ColorId", "Name")) %>
Run Code Online (Sandbox Code Playgroud)
小智 61
<%:
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
)
)
%>
Run Code Online (Sandbox Code Playgroud)
或者你不能写任何类,把这样的东西直接放到视图中.
Jul*_*tow 34
从模型中的词典开始,避免大量的指法
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"}
};
}
}
Run Code Online (Sandbox Code Playgroud)
在视图中将其转换为列表以供显示
@Html.DropDownListFor(m => m.Egg.Keys,
new SelectList(
Model.Egg,
"Key",
"Value"))
Run Code Online (Sandbox Code Playgroud)
小智 32
您好,我是如何在一个项目中做到的:
@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"})
Run Code Online (Sandbox Code Playgroud)
我希望它可以帮助某人.谢谢
Joe*_*und 12
或者,如果它来自数据库上下文,您可以使用
@Html.DropDownListFor(model => model.MyOption, db.MyOptions.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }))
Run Code Online (Sandbox Code Playgroud)
带有“请选择一项”
@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" })
Run Code Online (Sandbox Code Playgroud)
从代码派生而来:Master Programmer && Joel Wahlund ;
国王参考:https: //stackoverflow.com/a/1528193/1395101 JaredPar ;
谢谢首席程序员 && Joel Wahlund && JaredPar ;
祝你好运的朋友。