Tidying Your ASP.NET MVC Controllers

I’m a big believer of thin controllers. Here are some of the things you can do prevent your controller from bloating.

Move non-HTTP concerns somewhere else
This is sort of a given but it’s worth repeating over and over again. I view my controllers as an HTTP conduit. It ties my presentation to my business logic. For that, I am very particular what I put inside controller and in effect, handlers (methods). They usually fall into two main groups: request handling and session management. Everything else, I move them somewhere. Business logic usually morph into a service class while HTTP helpers turn into, well, helper classes. 

Use Partial Classes
About a year ago, we developed a habit to group controller’s handlers into partial classes. This creates clarity. For example, we group them by Views (ActionResult). So any method related to ‘/products/create’ like ‘/products/get-suppliers’ and ‘/products/get-categories’ will belong in one partial class. Altogether, ‘/products’ belong in one controller. You can create a “shared” partial class where common properties (or methods) are placed.

Model Binding is your best friend
I won’t go into model binding but simply put, you should be doing it. This forces you to move some validations to your presentation layer. Additionally, control the number of your handler’s parameters. My magic number is three, if it exceeds that, I wrap them to a class. 

Catch server-side validations
For server-side validations, I let controllers catch the errors instead of throwing them. For example, when saving a product, throw validation errors in your service class and have your handler catch it.