Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render derived types of a class differently?

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?

like image 460
Sedat Kapanoglu Avatar asked Oct 10 '13 13:10

Sedat Kapanoglu


1 Answers

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.

like image 65
Jamie Dixon Avatar answered Oct 01 '22 05:10

Jamie Dixon