Skip to content Skip to sidebar Skip to footer

Use Dropdownlistfor With Foreach In Asp.net Mvc View?

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

Solution 1:

I have a View with a foreach loop for a list property of the mode

I would recommend you to 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>

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 named XXX.cshtml where XXX is the type name used in your main view model collection.

Solution 2:

Have you tried:

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

Solution 3:

use this syntax:

@Html.DropDownListFor(model => model.Level, newSelectList(Model.levelasSystem.Collections.IEnumerable, "VALUE_FIELD", "TEXT_FIELD", YOURPROPERTYNAME)

Solution 4:

MVC will create the loop. Just use an editor template, partial view in special folder, and the rest works 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);

Post a Comment for "Use Dropdownlistfor With Foreach In Asp.net Mvc View?"