参见英文答案 >
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和一个保存选择的字段.
> 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> }
解决方法
你可能应该使用
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)
这将自动枚举您的集合并为集合中的每个项目呈现编辑器模板.