Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sharing methods between multiple controllers C# MVC4

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.

like image 865
Xaxum Avatar asked Feb 27 '13 20:02

Xaxum


People also ask

Can it possible to share a view across multiple controllers?

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.

Can we call method from one controller to another controller?

Yes, you can call a method of another controller. The controller is also a simple class.

Can two different controllers access a single view in MVC?

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.


1 Answers

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
}
like image 61
Oded Avatar answered Oct 12 '22 00:10

Oded