13

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?

float
  • 1,265
  • 5
  • 22
  • 38
  • You cannot use a `foreach` loop to generate form controls for a collection - refer [this answer](http://stackoverflow.com/questions/30094047/html-table-to-ado-net-datatable/30094943#30094943) for an explanation) –  Sep 28 '16 at 01:26

2 Answers2

11

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.

Ian Routledge
  • 4,012
  • 1
  • 23
  • 28
5

Assuming count start in 0, and your action post method receive a parameter of type ViewModel, you can try this for bind the MaterialId for each dropdown:

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>       
}
  • Thanks! I made changes to your answer. Answer from @Ian Routledge fits better as it uses basic mvc techniques. – float Apr 16 '13 at 12:32