asp.net-mvc @Html.DropDownListFor 如何添加选项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9293878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@Html.DropDownListFor How to add option?
提问by Shane LeBlanc
@Html.DropDownListFor(model => model.ZipFile, new SelectList(ViewBag.ZipFiles))
The above code creates me a select list just fine. But I want to make the selection optional. Unfortunately there is no empty option and I'd like to add one in. How would I do this?
上面的代码为我创建了一个选择列表就好了。但我想让选择成为可选的。不幸的是,没有空选项,我想添加一个。我该怎么做?
回答by Darin Dimitrov
By using the proper DropDownListFor overload:
@Html.DropDownListFor(
model => model.ZipFile,
new SelectList(ViewBag.ZipFiles),
"-- please select a zip file --"
)
回答by user5093080
@Html.DropDownListFor(model => model.Country, new List<SelectListItem>
{
new SelectListItem { Text = "India", Value = "1"},
new SelectListItem { Text = "USA", Value = "2"},
new SelectListItem { Text = "Sreelanka", Value = "3"},
new SelectListItem {Text = "Africa",Value="4"},
new SelectListItem { Text = "China", Value = "5" },
new SelectListItem { Text = "Austraila", Value = "6" },
new SelectListItem { Text = "UK", Value = "7" }
}, "Select Country",
new {@Style = "Width:500px;height:40px;",
@class = "form-control input-lg"})
回答by Giscard Biamby
In the controller, when you set ViewBag.ZipFiles, add a SelectListItem to that collection.
在控制器中,当您设置 ViewBag.ZipFiles 时,将 SelectListItem 添加到该集合。

