我正在尝试使用 foreach 循环生成的 SelectListItems 在我的 View 中填充 DropDownListFor,该循环遍历我的 ViewModel 中的字符串列表。
这是我在 ViewModel 中使用的属性:
public string Selected {get; set;}
public List<string> Strings {get; set;}
这是我的 View 语法:
@Html.DropdownListFor(
model => model.Selected,
new List<SelectListItem>
{
foreach(var answer in Model.Strings)
{
new SelectListItem
{
Value = answer, Text = answer
};
}
},
new { htmlAttributes = new { @class = "form-control" } })
Visual Studio 在“foreach”下抛出一个错误:
} expected
) expected
; expected
最后一个 ) 下的另一个错误是:
new{
; expected
} expected
我不确定我做错了什么或如何消除这些错误。任何建议将不胜感激。谢谢。
最佳答案
List<SelectListItem> item = Model.Strings.ConvertAll(answer =>
{
return new SelectListItem()
{
Text = answer.ToString(),
Value = answer.ToString()
};
});
@Html.DropDownListFor(model => model.Selected, item, new { htmlAttributes = new { @class = "form-control" } })
关于asp.net-mvc - MVC Razor 有没有办法通过从 List<string> ViewModel 生成 SelectListItems 来填充 DropdownListFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63607435/