【问题标题】:Nested Display Templates In RazorRazor 中的嵌套显示模板
【发布时间】:2012-02-17 05:41:41
【问题描述】:

我目前正在掌握 ASP.Net MVC 3 和 Razor 模板引擎,但我遇到了一个我无法完全掌握的问题 - 所以请向 StackOverflow 社区寻求帮助!

假设我有一个看起来像这样的视图模型层次结构:

public class Foo {
    public string FooTitle { get; set; }
    [UIHint("BarList")]
    public IList<Bar> BarList { get; set; }
}

public class Bar {
    public string BarTitle { get; set; }
}

一切都相当简单,我相信你会同意的。要使用此视图模型,我有以下内容:

~/Views/Home/Index.cshtml

@model Foo

<h1>@Model.FooTitle</h1>
@Html.DisplayFor(m => m.BarList)

~/Views/Home/DisplayTemplates/BarList.cshtml

@model IEnumerable<Bar>

<div class="bar-list">
@Html.DisplayForModel()
</div>

~/Views/Home/DisplayTemplates/Bar.cshtml

@model Bar

<p>@Model.BarTitle</p>

我希望在执行 View 时找到要显示的 Bar.cshtml 的内容,但渲染似乎没有进一步嵌套 BarList.cshtml

我在这里做错了什么?

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:

    如果您遵循约定,则不需要中介 BarList.cshtml 模板或 UIHint

    public class Foo {
        public string FooTitle { get; set; }
        public IList<Bar> BarList { get; set; }
    }
    
    public class Bar {
        public string BarTitle { get; set; }
    }
    

    查看(~/Views/Home/Index.cshtml):

    @model Foo
    <h1>@Model.FooTitle</h1>
    <div class="bar-list">
        @Html.DisplayFor(m => m.BarList)
    </div>
    

    显示模板(~/Views/Home/DisplayTemplates/Bar.cshtml):

    @model Bar
    <p>@Model.BarTitle</p>
    

    并且Bar.cshtml 模板将自动为BarList 集合的每个元素呈现。

    【讨论】:

    • 我知道这一点,但我有一种情况,我想在属于此控制器的不同视图中重新使用列表,并且我不想必须指定封闭
      每次
    【解决方案2】:

    我怀疑你仍然有这个问题,但这是正确的解决方案

    ~/Views/Home/DisplayTemplates/BarList.cshtml

    @model IEnumerable<Bar>
    <div class="bar-list">
    @foreach (var bar in Model) {
        @Html.DisplayFor(c => bar)
    }
    </div>
    

    【讨论】:

      【解决方案3】:

      将所有这些显示模板移至: ~/Views/共享/DisplayTemplates/

      编辑:遍历每个栏怎么样?

      @model IEnumerable<Bar>
      <div class="bar-list">
      @foreach (var bar in Model) {
          @Html.DisplayForModel(bar)
      }
      </div>
      

      【讨论】:

      • 将模板移动到共享而不是特定视图不能解决我的问题。
      • 奇怪。我在我的应用程序中做了完全相同的事情,而且效果很好。试试上面的代码
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 2016-04-01
      相关资源
      最近更新 更多