我有一个带有 foreach 循环的 View ,用于模型的列表属性。现在,我希望能够让用户使用下拉列表设置列表中每个项目的值。但我不知道该怎么做。当它不在 foreach 循环中时,我使用过类似的东西:
@Html.DropDownListFor(model => model.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, Model.Level))
但是当我需要在循环中引用 item.Level 时,我该怎么做呢?这是我的查看代码:
<div id="formDiv">
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Ny arbetserfarenhet</legend>
<table>
<tr>
@*<th></th>*@
<th>
Program
</th>
<th>
Nivå
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@item.Program.Name
</td>
<td>
@item.Level
</td>
</tr>
}
</table>
</fieldset>
}
</div>
最佳答案
I have a View with a foreach loop for a list property of the mode
我建议您避免在 View 中编写循环,而使用编辑器模板。所以:
@model IEnumerable<AppName.Models.ModelName>
<div id="formDiv">
@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Ny arbetserfarenhet</legend>
<table>
<tr>
<th>
Program
</th>
<th>
Nivå
</th>
</tr>
@Html.EditorForModel()
</table>
</fieldset>
}
</div>
并在相应的编辑器模板(~/Views/Shared/EditorTemplate/ModelName.cshtml
)中:
@model AppName.Models.ModelName
<tr>
<td>@Model.Program.Name</td>
<td>
@Html.DropDownListFor(
model => model.Level,
new SelectList(
Enumerable.Range(1, 5).Select(x => new { Value = x, Text = x }),
"Value",
"Text"
)
)
</td>
</tr>
因此,将为模型中的每个元素(这是某种类型的集合)呈现编辑器模板。重要的是编辑器模板必须位于 ~/Views/Shared/EditorTemplates
中并命名为 XXX.cshtml
,其中 XXX
是类型主视图模型集合中使用的名称。
关于asp.net - 在 Asp.Net MVC View 中使用 dropdownlistfor 和 foreach 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5420471/