When should I create new Controller class in Asp.net MVC (Design Question)?
Before I ask the question, here is my understanding about Controller in MVC pattern.
- Controller is Application Layer (in DDD)
- It controls Application flow.
- It is kept thin
- It controls unit of work (a.k.a Transaction)
My question is "when should I create new Controller class?". I'll take an example as DinnerController in NerdDinner.
- Is it the controller for Dinner Module? (Is it module? IMO, it is too small for module)
- If it is, should I create controller for each module? And will the controller become fat?
- If it is not, when should I create new controller?
I personally prefer to create Controller class per use case. For example, CreateDinnerControllelr, EditDinnerController, ListDinnerController, SearchDinnerController, etc. But there are a few drawbacks IMO such as
- Sometimes, it violates DRY principle (it might need to create the same ViewModel in two place, e.g. Create and Edit might have DinnerViewModel)
- Need to explicitly define routing? (I still perfer route like /Dinner/Create, /D开发者_高级运维inner/Edit/1)
Thanks in advance.
Common practice is to create a controller associated with each view. When the application is using Restful URL design, this usually maps to the index, new, edit and delete actions. You can then map an method to handle each action.
http://example.com/examples/1/edit - maps to edit method on ExamplesController
http://example.com/examples/1/new - maps to new method on ExamplesController
http://example.com/examples - maps to index method on ExamplesController
http://example.com/examples/1/delete - maps to delete method on ExamplesController
http://example.com/users/1/edit - maps to edit method on UsersController
http://example.com/users/1/new - maps to new method on UsersController
http://example.com/users - maps to index method on UsersController
http://example.com/users/1/delete - maps to delete method on UsersController
After working on ASP.net MVC and rails, I think Controller should create per Resource (in the REST style application).
精彩评论