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.
.\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?
@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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With