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.
Yes, It is possible to share a view across multiple controllers by putting a view into the shared folder. By doing like this, you can automatically make the view available across multiple controllers.
Yes, you can call a method of another controller. The controller is also a simple class.
Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With