How to build MVC Views that work with polymorphic domain model design

asp.net-mvcrazor

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?

Best Answer

Actually, building individual views for each of the IContract classes would not be breaking DRY -- presumably they have some different info with different needs. You aren't repeating yourself, you are successfully using polymorphisim.

I had a somewhat similar conoundrum for a project MVC1 project -- before DisplayFor provided a pretty good built-in solution. We used MVC Contrib's RenderAction delegates to send the polymorphic object off to a specialized controller that was responsible for dispatching things to the appropriate rendering pipeline. The internals get a bit squirrely, but it has been a rock solid system for us for 3 years or more.

Related Topic