Tim Murphy's .NET Software Architecture Blog

May 2014 Entries

Enhancing Your Model In MVC 5


Simple views in ASP.NET MVC 5 are simple, but once you start getting a lot of conditional content formatting in the view things can get very messy.  Once you get to the point where your Razor code has way to many if/else blocks and they start repeating you have to come up with a way to abstract and simplify your code.  I looked at functions and partial views as possible solutions.  Both of these have their place but an alternative that you may want to entertain is implementing your model as more than just a DTO (data transfer object).

The advantage that that this approach gives you is that you can more directly take advantage of the data in the model.  If you create a function in Razor you need to either have page variables or pass in a number of parameters to accomplish the same ends.  You can use the return value of your methods to set attributes in your HTML or simply to compress your code.

This does break the MVC pattern strictly speaking, but as I always suggest you should use standards as guidelines and not absolutes.  Follow the pattern as long as it makes sense and when it gets in the way do what needs to be done to achieve your goals.  This is one alternative for a specific problem type.  Use it for what it is.