I have a group of "benefits" which are of different types but all inherit from BaseBenefit
class. That List<BaseBenefit>
is then used on a view. What's the best practice here in order to present them?
I though of casting check by if's in the view but then that seemed to break the rule of a "stupid IU". I can though include a property for each benefit so that it will have an enum
for it's real type but I still need to check which is which with if's.
Any idea?
You could use display templates. So in the main view:
@Html.DisplayFor(x => x.Benefits)
where Benefits
is the property on your view model of type List<BaseBenefit>
. Now all you have to do is to define display templates for the different possible types:
~/Views/Shared/DisplayTemplates/SpecificBenefit1.cshtml
:
@model SpecificBenefit1
...
~/Views/Shared/DisplayTemplates/SpecificBenefit2.cshtml
:
@model SpecificBenefit2
...
The location and name of the display template is important. They must be located in the ~/Views/Shared/DisplayTemplates folder or if they won't be reused between controllers you could also define them in the ~/Views/SomeController/DisplayTemplates
folder. The name of the template must be the same as the type of the elements in the list.
When you use DisplayFor in the main view on an enumerable property ASP.NET MVC will automatically invoke the corresponding display template for each element of this list.
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