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>
use this syntax:
Have you tried:
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.MVC will create the loop. Just use an editor template, partial view in special folder, and the rest works like magic.
Editor Template
View