Reputation: 3675
I have the same method I call in six controllers. Right now I copy and paste between each of the controllers. All the controllers are in the same namespace. The method returns a bool based on the passed id. For example:
public bool CheckSubmission(int id =0)
{
Get Records from DB with criteria
If Record available return true
else return false
}
I have been away from C++ C# for awhile and can't find how to write these once. I know in Rails I can put the shared functions in ApplicationController. I have seen several Questions on SO about this but not a clear example, they are more along the lines read up on OOP. Any help would be appreciated as I get back into this.
Upvotes: 22
Views: 14964
Reputation: 498904
Create a ControllerBase
class that inherits from Controller
, place this method in it.
Have your controllers inherit from your base controller - they will get this implementation to use.
public class ControllerBase : Controller
{
public bool CheckSubmission(int id = 0)
{
Get Records from DB with criteria
If Record available return true
else return false
}
}
public class SomethingController : ControllerBase
{
// Can use CheckSubmission in here
}
Upvotes: 37