create many DropDownListFor in foreach-loop

float picture float · Apr 16, 2013 · Viewed 14.4k times · Source

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; }
}

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

Something like this:

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

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

Answer

Ian Routledge picture Ian Routledge · Apr 16, 2013

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.