asp.net - 在 Asp.Net MVC View 中使用 dropdownlistfor 和 foreach 吗?

标签 asp.net asp.net-mvc-3 foreach html.dropdownlistfor

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

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

但是当我需要在循环中引用 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>

最佳答案

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

我建议您避免在 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>

并在相应的编辑器模板(~/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>

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

关于asp.net - 在 Asp.Net MVC View 中使用 dropdownlistfor 和 foreach 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5420471/

相关文章:

php - 在不知道字段 php 的情况下循环遍历 fetchall

c# - 将数据集转换为 XML

c# - ASP.NET 中的布局问题 GridView

asp.net-mvc-3 - 如何在 MVC 3 中增加 session 超时

r - 并行处理的句子生成会产生乱码结果

php - 为每个结果输出特定的数组键

c# - SqlDataSource UpdateCommand 参数未更改

c# - 使用 C# : 比较和删除数据表行

entity-framework - 我如何 ModelBind 与 MVC 3 和 Entity Framework Code First 的多对多关系?

asp.net-mvc - 我正在寻找有关自定义 MVC3 编辑器模板的高级资源