创建的foreach循环不少DropDownListFor [英] create many DropDownListFor in foreach-loop

查看:310
本文介绍了创建的foreach循环不少DropDownListFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要动态地创建DropDownLists了一个列表,它提供选择列表和一个字段,以保存选择的。

I want to create DropDownLists dynamically out of a List, which supplies the SelectList and a field where to save the selection.

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列表循环和动态创建DropDownLists。

In the view, I want to loop through the materialSelect List and create the DropDownLists dynamically.

事情是这样的:

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我需要选择的值。有没有人有一个想法如何解决这个问题?

At the HttpPost ActionResult I need to get the selected values. Does anyone has an idea how to solve this?

推荐答案

您或许应该使用的 EditorTemplates 。这允许你excatly你描述什么做的。如果你创建一个强类型的局部视图〜/查看/共享/ EditorTemplates / Material_Select.cshtml(视图已被命名为相同型号),看起来像:

You should probably be using EditorTemplates. These allow you to do excatly what you're describing. If you create a strongly-typed partial view in ~/Views/Shared/EditorTemplates/Material_Select.cshtml (the view has to be named the same as the model) that looks like:

@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>

然后在你的整体形式可以只要致电:

Then in your overall form you can just call:

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

这将自动列出你的收集和呈现集合中的每个项目的编辑模板。

Which will automatically enumerate your collection and render the editor template for each item in the collection.

这篇关于创建的foreach循环不少DropDownListFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆