【问题标题】:Why do the ASP.NET MVC template views use Html.DisplayFor to display data that is not part of the model?为什么 ASP.NET MVC 模板视图使用 Html.DisplayFor 来显示不属于模型的数据?
【发布时间】:2013-09-12 22:25:36
【问题描述】:

我正在学习 ASP.NET MVC 4。一些默认模板视图包含如下内容:

@model IEnumerable<SomeModel>
...
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Property1)
</td>
        <td>
            @Html.DisplayFor(modelItem => item.Property2)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}

我的理解是DisplayFor接受一个表达式,其中输入参数是视图的模型,返回值是任何对象,并为返回的对象找到合适的DisplayTemplate。

基于此,我明白为什么DisplayFor(modelItem =&gt; item.Property1) 有效,但感觉这不是正确的选择。如果我根本不使用modelItem 参数,为什么要使用DisplayFor?没有像GetDisplayTemplate(item.Property1)这样的方法吗?

【问题讨论】:

  • 我认为您发现的独特情况是您的模型是IEnumerable&lt;T&gt;。情况并非总是如此。然后,说@Html.DisplayFor(modelItem =&gt; modelItem.Property1); 是有道理的。例如,如果您有一个渲染每个项目的局部视图.. 以上将是正确的。
  • @Simon:为什么DisplayFor 与模型的类型相关联?即,为什么我不能写像@Html.DisplayFor&lt;SomeType&gt;(item =&gt; item.Property1) 这样的东西?
  • 这将是 MVC 框架设计者的问题:P
  • 看这个所以问答,我想答案在最后2段中解释了,为什么会这样:stackoverflow.com/questions/10097995/…

标签: c# .net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

从技术上讲,正如您所说,modelItem 完全未使用。这是无参数 lambda 的示例。在这种情况下,我倾向于使用 _=>。我这样做是因为我们已经习惯了,尽管我认为它看起来确实有点奇怪。在循环列表时,它可以更容易地生成 editorfor 等。据我所知,没有其他调用 DisplayFor/EditorFor 的强类型方法

看这个问题解释Is there a better way to express a parameterless lambda than () =>?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2020-09-06
    • 1970-01-01
    • 2010-11-11
    • 2011-01-14
    • 2014-01-07
    相关资源
    最近更新 更多