Use dropdownlistfor with foreach in Asp.Net MVC View?

I have a view with a foreach loop for a model list property. Now I want the user to be able to set the value of each of the elements in the list using the drop-down list. But I do not know how to do this. I used something like this when it is not in the foreach loop:

@Html.DropDownListFor(model => model.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, Model.Level)) 

But how to do this when I need to reference item.Level in a loop? Here is 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> 
+4
source share
4 answers

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.

+7
source

You tried:

 @Html.DropDownListFor(m => item.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, item.Level)) 
+4
source

use this syntax:

  @Html.DropDownListFor(model => model.Level, new SelectList(Model.level as System.Collections.IEnumerable, "VALUE_FIELD", "TEXT_FIELD", YOUR PROPERTY NAME) 
0
source

MVC will create a loop. Just use the editor template, a partial view in a special folder, and the rest work like magic.

Editor Template

 @model Models.AdditionalAccountingLine @Html.HiddenFor(m => m.IsRequired) @Html.DropDownListFor(m => m.FieldValue, new SelectList(@Model.FieldValueOptions, "Key", "Value"), "") 

View

 @Html.EditorFor(m => m.AdditionalAccountingLines); 
0
source

Source: https://habr.com/ru/post/1345096/


All Articles