2011-03-11 93 views
1

我目前正在處理ASP.Net MVC 3和Razor模板引擎,但我遇到了一個我無法完全掌握的問題 - 所以結束了StackOverflow社區來幫忙!Razor中的嵌套顯示模板

比方說,我有一個視圖模型的層次結構,看起來像這樣:

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

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

都相當簡單,我相信你會同意。要使用該視圖模型我有以下幾點:

〜/瀏覽/首頁/ Index.cshtml

@model Foo 

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

〜/瀏覽/首頁/ DisplayTemplates/BarList.cshtml

@model IEnumerable<Bar> 

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

〜/瀏覽/首頁/ DisplayTemplates/Bar.cshtml

@model Bar 

<p>@Model.BarTitle</p> 

我希望找到的Bar.cshtml的要顯示的內容,當我執行我的視圖,但渲染似乎沒有窩進一步指出BarList.cshtml

我在做什麼錯在這裏?

回答

3

如果你按照約定你不需要中介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> 

和0123將自動爲BarList集合的每個元素呈現模板。

+0

我知道這一點,但我有我想在屬於此控制器的不同視圖中重新使用該列表的情況,並且我不希望每次都必須指定包含的

2011-03-11 13:14:28

0

移動所有這些顯示模板到: 〜/查看/ 共享/DisplayTemplates/

編輯:關於通過各條迭代是什麼?

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

將模板移至共享而不是特定視圖不能解決我的問題。 – 2011-03-28 09:43:12

+0

奇怪。我在我的應用程序中完成了完全相同的事情,並且工作正常。試試上面的代碼 – woopstash 2011-03-28 17:36:02

1

我懷疑你仍然有這個問題,但是這是正確的解決方案

〜/瀏覽/首頁/ DisplayTemplates/BarList.cshtml

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