質問

I have a simple product list, the products fall into two distinct categories and are displayed differently on the page depending on their category id.

Is it at all possible to nest DisplayTemplates of the same Model type e.g.

//DisplayTemplates/Product.cshtml
@model MyNameSpace.Product


@if (Model.CategoryId == (int)ASixthSenseCore.CategoryId.GiftCards)
{
    @Html.DisplayForModel("GiftCards")
}
else
{
    @Html.DisplayForModel("Merchandise")
}



//DisplayTemplates/GiftCards.cshtml
@model MyNameSpace.Product

<div>I am a Gift Card</div>


//DisplayTemplates/Merchandise.cshtml
@model MyNameSpace.Product

<div>I am Merchandise</div>


//My View
@mode List<MyNameSpace.Product>

@Html.DisplayForModel()

I've tried doing this and it doesn't break, but it doesn't work either, the Product template runs as expected - I've added some debug text which correctly outputs for each corresponding item in the Product List. I suspect there is some kind of blocking clause in the Template Engine to avoid it from disappearing up it's own backside with recursive calls to the same template being a possibility of this scenario, having said that I thought I would ask as this would be a handy way to deal with multiple DisplayTemplates for lists without having to iterate them with a foreach loop.

役に立ちましたか?

解決

Your code should work, assuming your templates are not in DisplayeTemplates folder.

I would create separate subclasses of Product and create templates for them. This will keep the code cleaner and you wouldn't have to put if statements everywhere.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top