在Asp.Net MVC View中使用dropdownlistfor和foreach?

And*_*ers 4 asp.net foreach html.dropdownlistfor asp.net-mvc-3

我有一个带有foreach循环的View,用于模型的list属性.现在,我希望能够让用户使用下拉列表设置列表中每个项目的值.但我不知道该怎么做.当它不在foreach循环中时,我使用了类似的东西:

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

但是当我需要在循环中引用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>
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 8

我有一个带有foreach循环的View,用于模式的列表属性

我建议你避免在视图中编写循环以支持编辑器模板.所以:

@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>
Run Code Online (Sandbox Code Playgroud)

并在相应的编辑器模板(~/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>
Run Code Online (Sandbox Code Playgroud)

因此,将为模型中的每个元素(这是某种类型的集合)呈现编辑器模板.最重要的部分就是编辑模板必须位于~/Views/Shared/EditorTemplates并命名XXX.cshtml哪里XXX是你的主视图模型集合中使用的类型名称.


B Z*_*B Z 5

你有没有尝试过:

@Html.DropDownListFor(m => item.Level, new SelectList(new[] { 1, 2, 3, 4, 5 }, item.Level))
Run Code Online (Sandbox Code Playgroud)