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

c# – 在foreach-loop中创建许多DropDownListFor

发布时间:2020-12-15 17:44:26 所属栏目:百科 来源:网络整理
导读:参见英文答案 DropDownListFor does not select value if in for loop6个 How to set default value to select list in MVC during run time2个 我想从List中动态创建DropDownLists,它提供SelectList和一个保存选择的字段. public class ViewModel{ public L
参见英文答案 > DropDownListFor does not select value if in for loop6个
> How to set default value to select list in MVC during run time2个
我想从List中动态创建DropDownLists,它提供SelectList和一个保存选择的字段.
public class ViewModel
{
    public List<Material_Select> materialSelect { get; set; }
}

public class Material_Select
{
    public SelectList selectList { get; set; }
    public int MaterialId { get; set; }
}

在视图中,我想循环遍历materialSelect List并动态创建DropDownLists.

像这样的东西:

int count = 0;
foreach (var item in Model.materialSelect)
{
    count++;
    <div class="editor-label">
        @Html.LabelFor(model => model.materialSelect)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(item.MaterialId,item.selectList)
    </div>       
}

在HttpPost ActionResult我需要获取选定的值.有谁知道如何解决这个问题?

解决方法

你可能应该使用 EditorTemplates.这些允许你疯狂地做你所描述的.如果在?/ Views / Shared / EditorTemplates / Material_Select.cshtml中创建强类型的局部视图(视图必须与模型命名相同),如下所示:
@model Material_Select

<div class="editor-label">
    @Html.LabelFor(m => m.MaterialId)
</div>
<div class="editor-field">
    @Html.DropDownListFor(m => m.MaterialId,Model.selectList)
</div>

然后在您的整体表格中,您可以致电:

@Html.EditorFor(m => m.materialSelect)

这将自动枚举您的集合并为集合中的每个项目呈现编辑器模板.

(编辑:李大同)

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

    推荐文章
      热点阅读