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?
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.
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>
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With