问题描述
我正在尝试将Html.DropDownListFor与ViewBag中的字符串列表一起使用.
I am trying to use Html.DropDownListFor with the list of strings from a ViewBag.
基本上,我得到了一个ViewBag,其中包含诸如"Adam","Tom","Mike"等之类的字符串列表.
Basically I got a ViewBag with a list of string like "Adam","Tom","Mike" etc...
我在徘徊,是否有可能将此列表传递给DropDownListFor,其中Value和text都是列表中的项.
I was wandering if it is possible to pass this list in to DropDownListFor where both Value and text are the items from my list.
我无法在此处使用foreach ...
I wasn't able to use foreach here...
带有硬编码的示例:
@Html.DropDownListFor(model => model.Name, new SelectList(
new List<Object>{
new { value = "Adam" , text = "Adam" },
new { value = "Tom" , text = "Tom" },
new { value = "Mike" , text = "Mike" },
new { value = "Jake" , text = "Jake" },
},
"value",
"text",
2))
推荐答案
您可以从字符串列表中生成 SelectListItem
的集合,并将其与 DropDownListFor
帮助器一起使用方法.
You can generate a collection of SelectListItem
s from the list of strings and use that with DropDownListFor
helper method.
var names = new List<string> {"Adam", "Sam"};
ViewBag.Names = names.Select(f => new SelectListItem() {Value = f, Text = f});
并在视图中
@Html.DropDownListFor(f=>f.Name, ViewBag.Names as IEnumerable<SelectListItem>,
"select one")
这篇关于asp.net MVC-在DropDownListFor中使用字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!