加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 07:31:40 所属栏目:asp.Net 来源:网络整理
导读:我有一个带有foreach循环的View,用于模型的list属性.现在,我希望能够让用户使用下拉列表设置列表中每个项目的值.但我不知道该怎么做.当它不在foreach循环中时,我使用了类似的东西: @Html.DropDownListFor(model = model.Level,new SelectList(new[] { 1,2,3
我有一个带有foreach循环的View,用于模型的list属性.现在,我希望能够让用户使用下拉列表设置列表中每个项目的值.但我不知道该怎么做.当它不在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

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

@model IEnumerable<AppName.Models.ModelName>
<div id="formDiv">
    @using (Html.BeginForm(null,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是主视图模型集合中使用的类型名称.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读