Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I create a new controller class in ASP.NET MVC?

I'm learning MVC and am having trouble deciding when I should create a new controller versus just adding an action and view associated with an existing controller. On the one hand, Single Responsibility would seem to say a controller should be limited to a few actions. When I try this, though, the number of classes grows exponentially (model, views and controller for each)- to the point I wonder if I'm going overboard.

For example, the default AccountController has Login, ChangePassword, and Register actions. I would tend to instead create a LoginController, PasswordController, and ProfileController, and related model classes. So where there was 1 class, there would be 3-6.

Is there any good rule of thumb on this?

like image 604
Daniel Avatar asked Jan 07 '09 23:01

Daniel


People also ask

When should I create a new controller in MVC?

You should dedicate a controller for each model type you're manipulating. The controller acts as a collection of actions that act upon those models. This is generally the rule of thumb, but sometimes a controller's scope transcends a single model.

Why do we need controller class?

Controller . Controller class contains public methods called Action methods. Controller and its action method handles incoming browser requests, retrieves necessary model data and returns appropriate responses. In ASP.NET MVC, every controller class name must end with a word "Controller".

When creating a new controller What class do you inherit from?

Right Click on Controllers folder and select Add new item and select the MVC Controller in the Template. This will create an Empty Controller. The Controllers in ASP.NET Core Inherit from Controller class which in turn inherits from the ControllerBaseClass. These two base classes provide several useful helper methods.

What do controller classes do?

A controller class is normally a class part of the Model View Controller (MVC) pattern. A controller basically controls the flow of the data. It controls the data flow into model object and updates the view whenever data changes.


1 Answers

You should dedicate a controller for each model type you're manipulating. The controller acts as a collection of actions that act upon those models. This is generally the rule of thumb, but sometimes a controller's scope transcends a single model.

The AccountController deals with all things authentication related. This is an example of going beyond a single model's scope to encompass authentication in general. What are the key parts of authentication? Retrieving users, changing passwords, etc.

like image 195
Soviut Avatar answered Sep 24 '22 12:09

Soviut