Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Presenting in a view a model containing inheritance in MVC

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?

like image 683
Guy Z Avatar asked Feb 23 '23 04:02

Guy Z


1 Answers

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.

like image 143
Darin Dimitrov Avatar answered Mar 06 '23 07:03

Darin Dimitrov