使用多态模型绑定时将IEnumerable <derivedmodel>传递给视图</derivedmodel>

时间:2014-03-08 10:16:43

标签: c# asp.net-mvc polymorphism viewmodel model-binding

我找到了this answer,它帮助我理解了如何使用多态模型绑定,以避免为我拥有的每个派生模型创建单独的控制器。

但是,我并没有弄清楚如何将IEnumerable传递给我的EditorTemplates。通常,通过脚手架我的模型,我最终会在我的视图中使用IEnumerable,我可以使用foreach循环循环以显示所有内容。

像这样......

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.username)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.date)
        </td>
        ...

在常规控制器中我会使用return View(items.ToList());但是如何通过多态模型绑定实现相同的结果呢?

EDIT1: 这就是我的控制器的样子......

  public ActionResult Index()
        {

            List<Item> myList = new List<Item>()

            {
                new Derived1(),
                new Derived2()
            };

            var model = myList;
            return View(model);
        }

从索引我调用@ Html.EditorForModel()

在我的EditorTemplates中,我有这个......

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

现在就像你说的那样,似乎EditorForModel通过在列表中显示两个派生模型来完成它的工作,但只有DisplayNameFor工作......我无法使用DisplayFor来填充DB中的实际数据。有什么我做错了吗?

1 个答案:

答案 0 :(得分:0)

如果您已经拥有EditorTemplates,只需拨打@Html.EditorForModel(),而不是foreach循环。根据对象的类型,框架将选择正确的编辑器模板进行渲染。

相关问题