I am very new in ASP.NET MVC and Web stuff. I want to know how I should separate my page logic into different controllers. Like for example should I use HomeBuyProduct
or ProductBuy
. When there is a sign to move logic to the new separate controller? Should it be one Controller per page? What is the basic rules?
There’s a million ways to set up anything, but I will tell you that being new to MVC myself (but liking it so far), I typically do set up one Controller action “per page”. I’m sure you can abstract this differently as you master MVC, but for my first app, there’s a correlation between a single action in a controller and a single “page”.
Regarding the structure around home||product||buy etc, I’m setting mine up like
Home Controller:
- “http://root/” => home page
Products Controller:
- “http://root/products” => listing of all products, or product categories.
- “http://root/products/detail” => 404 error.
- “http://root/products/detail/50” => details of a single product with ID 50.
- “http://root/products/detail/50/add” => add that product to the cart
Cart Controller:
- “http://root/shoppingcart” => show cart details for current user.
- “http://root/shoppingcart/checkout” => show checkout details.
I’m trying to follow the “Fat ViewModel, Skinny Controller” pattern, so my controller actions are just a couple lines long each. They just initialize Fat ViewModels and execute 1-2 methods on each model depending on what needs to be done. The models contain the bulk of the code.
And widgets that need to get re-used are made into their own ViewModel and the parent ViewModel has a child member of that reusable ViewModel class. The reusable ViewModel gets a view created for it and put into the “Shared/EditorTemplates” folder. This view is called from the “EditorFor” helper thats put in the main ViewModel’s view.
It sounds to me like you are still looking at it in terms of web forms. You have to change your thinking a little. Don’t think of it as “controllers per page”. There are no “pages”, there are views. Controllers direct traffic. They take in input from the user and decide which view should bre presented. The models are your business logic…
How you set it up is a function of the site you are creating and a matter of personal preference. But, the most important thing is that you need to redirect your mind from web forms.