I have a view with a foreach loop for a mode list property
I would recommend that you avoid writing loops in your views in favor of editor templates. So:
@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>
and in the corresponding editor template ( ~/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>
Thus, the editor template will be displayed for each element of your model (which is a set of some type). The important part is that the editor template should be located in ~/Views/Shared/EditorTemplates and named XXX.cshtml , where XXX is the type name used in your main model collection.
source share