Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create many DropDownListFor in foreach-loop [duplicate]

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?

like image 386
float Avatar asked Apr 16 '13 10:04

float


2 Answers

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.

like image 50
Ian Routledge Avatar answered Sep 18 '22 12:09

Ian Routledge


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>       
}
like image 44
Carlos Corral Carvajal Avatar answered Sep 18 '22 12:09

Carlos Corral Carvajal