ASP.NET MVC – Using Partial Class for Controller

asp.net-mvc

I have a webpage and frontend contains pages for Customer, Product and Order part and other parts may be added.

The actual implementation is that every part(modul) has its own Controller and every part(modul) has about 8 pages.

  • CustomerController
  • ProductController
  • OrderController
  • Other parts

Each page has its methods in the related partial class. That means that Controller class is splitted to 8 files for example.

From the maintaince perspective it eliminate "fat controllers" but still i am not sure about this practice.

The example code:

// Customer Index page
    public partial class CustomerController : Controller
    {
        Database database = new Database();

        [HttpGet]
        public ActionResult Index() {...}

        [HttpPost]
        public ActionResult Index(CustomerModel model) {...}

        [HttpPost]
        public ActionResult Search(CustomerModel model) {...}

    }

// Customer AddOrUpdate page 
    public partial class CustomerController
    {   
        [HttpPost]
        public ActionResult AddOrUpdateCustomer(CustomerModel model) {...}
    }

// Customer Hierarchy page
    public partial class CustomerController
    {

        [HttpGet]
        public ActionResult Hierarchy(){...}

        [HttpPost]
        public ActionResult Hierarchy(HierarchyModel model){...}

        public ActionResult ApiGetHierarchyItem(int Id){ ... }

    }

the question is if the way of preventing Controller becoming fat by partial classes is good practice.

Best Answer

If you are starting from scratch you should have a controller for each page and not bloat a single controller. While partials may seem like a "good" idea, its still a single giant class with multiple responsibilities. Adding additional controllers is very simple and will reduce the overall complexity of your project.

If you are inheriting a solution where one controller was used for many pages and want to try to start correcting the issues then, as an initial first step of refactoring, breaking the monster into several files with partial classes is a sound plan. After you have broken the giant class into files that have a single responsibility you can change that file to be a class of its own with a single responsibility as you pay down the technical debt.