Better to have huge Controllers, or many controllers, in MVC?

Beep beep picture Beep beep · Jul 29, 2009 · Viewed 23k times · Source

We are building a fairly large HR application in ASP.NET MVC, and so far our controllers are becoming quite large. For example, we have an Employee controller, and all employee views are included (Personal info, employee deductions, dependents, etc). Each of these views might have multiple actions or subviews (e.g. CRUD). Each action is relatively small, but the controllers might have dozens of functions.

Are there any best practices for splitting controllers? Instead of having an Employee controller with dozens of views, would it be better too have one controller for each subtype (i.e. EmployeePersonalInfoController, EmployeeDeductionController, EmployeeDependentController)?

And finally, does it even matter?

Updated Clarification

My original concern was with CRUD actions. For example, let's consider Create and Delete ...

Current Actions in EmployeeController:

  CreateEmployee()
  DeleteEmployee()
  CreateEmployeeDeduction()
  DeleteEmployeeDeduction()
  CreateDependent()
  DeleteDependent()
  etc.

If the controllers were split:

  EmployeeController
    Create()
    Delete()
  EmployeeDeductionController
    Create()
    Delete()
  EmployeeDependentController
    Create()
    Delete()
  EmployeeBenefitController
    Create()
    Delete()
  etc.

In the 1st scenario, our ~100 screens get split into 8-10 large controllers. In the second, I'd probably have ~50 controllers.

Answer

Sam Wessel picture Sam Wessel · Jul 29, 2009

Partial classes allow you to spread your class across multiple files. That way you can group relevant areas of your controller into separate files, and yet they'll all still be part of the same controller. e.g.

EmployeeDeductionController.cs

public partial class EmployeeController
{
    public ActionResult Deduct()
    {
    }
    // etc
}

EmployeeBenefitController.cs

public partial class EmployeeController
{
    public ActionResult GiveBenefit()
    {
    }
    // etc
}