在foreach-loop中创建许多DropDownListFor

flo*_*oat 8 c# asp.net-mvc html-select html.dropdownlistfor

我想从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; }
}
Run Code Online (Sandbox Code Playgroud)

在视图中,我想循环遍历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>       
}
Run Code Online (Sandbox Code Playgroud)

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

Ian*_*dge 9

你可能应该使用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>
Run Code Online (Sandbox Code Playgroud)

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

@Html.EditorFor(m => m.materialSelect)
Run Code Online (Sandbox Code Playgroud)

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


小智 5

假设count从0开始,并且您的action post方法接收ViewModel类型的参数,您可以尝试使用它来为每个下拉列表绑定MaterialId:

foreach (var item in Model.materialSelect)
{
    count++;
    <div class="editor-label">
       Name for de dropdown
    </div>
    <div class="editor-field">
        @Html.DropDownList("materialSelect[" + count + "].MaterialId ", item.selectList)
        @Html.ValidationMessageFor(model => model.gradationId)
    </div>       
}
Run Code Online (Sandbox Code Playgroud)