I have an Item
class. I have around 10-20 derivatives of it each containing different types of data. Now when it comes to rendering different types of Item
, I'm forced to use likes of:
<div>
@if (Model is XItem)
{
... rendering logic 1 ...
}
@if (Model is YItem)
{
... rendering logic 2 ...
}
@if (Model is ZItem)
{
... rendering logic 3 ...
}
... goes on and on forever ...
</div>
Unfortunately @Html.DisplayFor()
does not work in this case because the Model
is type of Item
, DisplayTemplates\Item.cshtml
is displayed.
HTML helpers don't help either because of the same "if/is" chain.
I could incorporate rendering logic inside the classes themselves, and call @Model.Render()
but they belong to business logic, not presentation. It would be a sin.
There is only one option of @Html.Partial(Model.GetType().Name)
but it feels wrong. You expect a solution without meta-magic. Is there a better way?
Use Display Templates.
Inside your ~/Views/Shared/DisplayTemplates
folder you can add a view with the same name as your type.
When you do @Html.DisplayFor(item)
you'll get the view related to that specific type.
UPDATE
I just saw your comment RE DisplayFor so if this doesn't help i'll remove my answer.
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