How to build MVC Views that work with polymorphic domain model design?
Posted
by
Johann de Swardt
on Programmers
See other posts from Programmers
or by Johann de Swardt
Published on 2012-09-13T06:13:08Z
Indexed on
2012/09/13
15:50 UTC
Read the original article
Hit count: 392
asp.net-mvc
|Razor
This is more of a "how would you do it" type of question.
The application I'm working on is an ASP.NET MVC4 app using Razor syntax.
I've got a nice domain model which has a few polymorphic classes, awesome to work with in the code, but I have a few questions regarding the MVC front-end.
Views are easy to build for normal classes, but when it comes to the polymorphic ones I'm stuck on deciding how to implement them.
The one (ugly) option is to build a page which handles the base type (eg. IContract) and has a bunch of if statements to check if we passed in a IServiceContract or ISupplyContract instance. Not pretty and very nasty to maintain.
The other option is to build a view for each of these IContract child classes, breaking DRY principles completely. Don't like doing this for obvious reasons.
Another option (also not great) is to split the view into chunks with partials and build partial views for each of the child types that are loaded into the main view for the base type, then deciding to show or hide the partial in a single if statement in the partial. Also messy.
I've also been thinking about building a master page with sections for the fields that only occur in subclasses and to build views for each subclass referencing the master page. This looks like the least problematic solution? It will allow for fairly simple maintenance and it doesn't involve code duplication.
What are your thoughts? Am I missing something obvious that will make our lives easier? Suggestions?
© Programmers or respective owner