Ed Courtenay
Ed Courtenay

Reputation: 530

Nested Display Templates In Razor

I'm currently getting to grips with ASP.Net MVC 3 and the Razor templating engine, but I've come across an issue that I can't quite get to grips with - so over to the StackOverflow community to help!

Let's say that I have a View Model hierarchy that looks like this:

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

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

all fairly simple I'm sure you'll agree. To go with this View Model I have the following:

~/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>

I would expect to find the contents of Bar.cshtml to be displayed when I execute my View, but the rendering doesn't seem to nest further that BarList.cshtml

What am I doing wrong here?

Upvotes: 1

Views: 4066

Answers (3)

Kyle
Kyle

Reputation: 1172

I doubt you still have this issue but this is the correct solution

~/Views/Home/DisplayTemplates/BarList.cshtml

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

Upvotes: 1

jebcrum
jebcrum

Reputation: 908

Move all these Display Templates to: ~/Views/Shared/DisplayTemplates/

Edit: What about iterating through each bar?

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

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

You don't need the intermediary BarList.cshtml template nor UIHint if you follow the conventions:

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

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

View (~/Views/Home/Index.cshtml):

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

Display template (~/Views/Home/DisplayTemplates/Bar.cshtml):

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

and the Bar.cshtml template will automatically be rendered for each element of the BarList collection.

Upvotes: 3

Related Questions