在 Asp.Net MVC 视图中使用 dropdownlistfor 和 foreach 吗?
我有一个带有 foreach 循环的视图,用于模型的列表属性。现在,我希望能够让用户使用下拉列表设置列表中每个项目的值。但我不知道该怎么做。当它不在 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 model. Now, I want to be able to let the user set the value of each of the items in the list using a dropdownlist. But I'm not sure how to do that. I've used something like this when it is not in a foreach loop:
@Html.DropDownListFor(model => model.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, Model.Level))
But how do I do this when I need to reference item.Level in the loop instead? Here's my View code:
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我建议您避免在视图中编写循环,以支持编辑器模板。所以:
在相应的编辑器模板(
~/Views/Shared/EditorTemplate/ModelName.cshtml
)中:因此将为模型中的每个元素呈现编辑器模板(这是某种类型的集合) )。重要的是编辑器模板必须位于
~/Views/Shared/EditorTemplates
中并命名为XXX.cshtml
,其中XXX
是类型主视图模型集合中使用的名称。I would recommend you to avoid writing loops in your views in favor of editor templates. So:
and in the corresponding editor template (
~/Views/Shared/EditorTemplate/ModelName.cshtml
):So the editor template will be rendered for each element in your model (which is a collection of some type). The important part is that the editor template must be located in
~/Views/Shared/EditorTemplates
and namedXXX.cshtml
whereXXX
is the type name used in your main view model collection.你有没有尝试过:
Have you tried:
使用这个语法:
use this syntax:
MVC 将创建循环。只需使用编辑器模板,特殊文件夹中的部分视图,其余的就像魔术一样。
编辑器模板
查看
MVC will create the loop. Just use an editor template, partial view in special folder, and the rest works like magic.
Editor Template
View