I found this answer, which has helped me understand how to use polymorphic model binding in order to avoid creating a separate controllers for every derived models I have.
However, I didn't quite figure out how to pass a IEnumerable to my EditorTemplates. Normally, by scaffolding my models I would end up with a IEnumerable in my views which I can cycle with a foreach loop in order to display the all content.
Something like this...
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.username)
</td>
<td>
@Html.DisplayFor(modelItem => item.date)
</td>
...
In a regular controller I would use return View(items.ToList()); but how can I achieve the same result with polymorphic model binding?
Edit1: This is how my controller looks like..
public ActionResult Index()
{
List<Item> myList = new List<Item>()
{
new Derived1(),
new Derived2()
};
var model = myList;
return View(model);
}
From index I call @Html.EditorForModel()
And in my EditorTemplates I have this...
@model Gear.Models.Derived1
<h3>Phones</h3>
@Html.Hidden("ModelType", Model.GetType())
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(x => x.username)
</th>
<th>
@Html.DisplayNameFor(x => x.address)
</th>
<th></th>
</tr>
<tr>
<td>
@Html.DisplayFor(x => x.username)
</td>
<td>
@Html.DisplayFor(x => x.address)
</td>
</tr>
</table>
Now like you said, it seems like the EditorForModel is doing its job by displaying both derived model in the list but only DisplayNameFor works ...I can't get the field populated with actual data from the DB with DisplayFor. Is there something I'm doing wrong?