【问题标题】:Why is my statically typed partial view trying to render an unintended model type?为什么我的静态类型分部视图试图呈现非预期的模型类型?
【发布时间】:2013-10-30 17:42:21
【问题描述】:

在我的 ASP.NET MVC4 Web 应用程序中,我有一个局部视图。它只是一个局部视图,旨在显示一个表格,给定一组实体。它看起来像这样:

@model ICollection<Portal.Models.Matter>

<table class="table table-striped table-bordered table-hover">
    <thead>
        <tr>
            <th>Name</th>
            <th>Last Accessed</th>
            <th>Client</th>
        </tr>
    </thead>
    <tbody>

        @if (Model.Count > 0)
        {
            @Html.DisplayForModel()
        }
        else
        {
            <tr>
                <td colspan="3" class="text-muted text-centered">There are no Matters to display.</td>
            </tr>
        }

    </tbody>
</table>

我有一个 Matter 的 DisplayTemplate,它静态输入到单个 Matter 实体,它处理每个表格行的呈现。

由于某种原因,当这个部分被渲染时,它没有使用Matter DisplayTemplate 它只显示以下内容:

System.Collections.Generic.List`1[Portal.Models.Account]System.Collections.Generic.List`1[Portal.Models.Account]

现在,这个部分甚至没有绑定到Account 实体的集合。它绑定到Matter 实体的集合。那么,为什么@Html.DisplayForModel() 试图显示Accounts 的集合?在运行时,使用调试器,我可以看到 Model 实际上是 Matter 实体的集合,而不是 Account

我使用以下代码渲染这个部分:

@Html.Partial("~/Views/Matter/_Table.cshtml", Model.Client.Matters, new ViewDataDictionary())

【问题讨论】:

  • 你为什么将 Partial 传递给一个空的ViewDataDictionary
  • 我只是在测试它。不管有没有,都会发生同样的事情。
  • 您可以张贴您在~/Views/Shared/DisplayTemplates 文件夹中的所有文件的屏幕截图吗?
  • 当然,screen shot is here
  • 对于其他视图使用的局部视图,在控制器的命名文件夹之外,它们是否必须在共享文件夹中?

标签: asp.net asp.net-mvc razor partial-views


【解决方案1】:

我找到了解决方法,或者可能是解决方案,不确定。无论如何,我没有在ICollection 上使用DisplayForModel,而是遍历集合并在每个元素上使用DisplayFor

例如...

@model ICollection<Foo>

for (var item in Model)
{
    @Html.DisplayFor(m => item)
}

我想没有什么会迫使你在DisplayFor 中使用m 的属性。

【讨论】:

    猜你喜欢
    • 2013-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2019-08-31
    • 2011-08-24
    • 2010-10-26
    相关资源
    最近更新 更多