0

In an MVC application I have 2 controllers that deal with certain type of data. One controller is for an admin and the other is for a regular user. Some of the actions will be exactly the same for both controllers while some will be unique to a specific controller. Can I somehow save myself from having multiple copies of the same code?

Note that each of the controllers inherits from a different base class and I cannot directly redirect (url has to stay within one controller) from an action in one controller to an action in the other one.

jahu
  • 5,427
  • 3
  • 37
  • 64

4 Answers4

2

Why you need separate controller for same action?

I think you want follow DRY . Before please read:

Don't Repeat Yourself

Depend on you situation you can use a method in the separate class or use extension method. Also you can use separate controller for the action. Also you can think about your controllers and action.

  • Not all actions are the same, in fact only a few are. While some of the actions are the same, they will use different views and they are intended to have different urls. Using multiple controllers allows me to do just that. Now that I look at the code, I see that a common base controller should have been used, but this part of the application wasn't written by me and I don't have the time to fix it now. – jahu Apr 03 '14 at 12:03
2

Create a separate class to hold the logic repeated in your 2 controllers. Then call the logic from both controllers...

This helper class... is very usefull to clean of logic your controllers also...

Romias
  • 13,783
  • 7
  • 56
  • 85
1

You can either use Filters or you can share logic somewhere else, the simplest way being a public static method in one of the controllers (or somewhere else) that is called for both ActionMethods.

If you make a service call of some sort in both controllers, perhaps you can move the shared logic to a private method that is called by both service methods?

I agree with Shahrooz. While having the same code in multiple places is something that works quite well when writing the code initially it will bite you in the long run.

Laoujin
  • 9,962
  • 7
  • 42
  • 69
  • Now that I look at the code, I see that both controllers should have inherited the same base class, but they don't (this part of the application wasn't coded y me). I think I'll try adding static methods to one of the controllers. – jahu Apr 03 '14 at 11:54
0

Don't Repeat Yourself

I recommend you to use Attribute. Create a attribute that define that which user can enter action by role. Hope this will help you:

Community
  • 1
  • 1
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90