Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested @Html.DisplayFor(model => baseClass, "BaseClass") for base class template not rendering

Several sub-classes (e.g. Cheese) share common properties derived from a base class (Product) with properties like SKU, Name and Description.

To avoid duplication when rendering display/editor templates, I want each sub-class template (Cheese.cshtml) to render its unique fields below that of its shared common base class template (Product.cshtml).

However, casting from the derived class to the base class (Product)cheese and trying to display its template inside the sub-class template has no effect.

DisplayTemplate File structure:

.\Views\Shared\DisplayTemplates
    .\Product.cshtml -- renders common base class fields
    .\Cheese.cshtml -- renders unique class fields and calls Product.cshtml

Cheese.chtml:

@model Application.Data.Models.Cheese

@{
    var product = (Application.Data.Models.Part)Model;
}

Base Product Fields:
@Html.DisplayFor(x => products, "Product") @* no effect! *@

<div class="field">
    <div class="display-label">@Html.LabelFor(m => Model.UniqueProperty)</div>
    <div class="display-field">@Html.DisplayFor(m => Model.UniqueProperty)</div>
</div>

Casting to the base class and rendering the Product.cshtml template works fine from a View, but not from within the sub-class template.

How can I render a common template for my base class from within my sub-class templates?

like image 481
Petrus Theron Avatar asked Mar 13 '11 19:03

Petrus Theron


1 Answers

Solution Found

@Html.DisplayFor(...) cannot be nested, so you have to use @Html.Partial in your derived template like so:

@Html.Partial("~/Views/Shared/DisplayTemplates/Product.cshtml", product) %>

Or, if your file structure allows it, a more terse path:

@Html.Partial("DisplayTemplates/Product", product)
like image 78
Petrus Theron Avatar answered Nov 09 '22 08:11

Petrus Theron