Reputation: 10723
In MVC, for example I have 5 different controller files. In all of them I have a method for saving an image. Is there a way to put this method on one place and every controller method to access it, instead of writing it in every controller? I tried
MyController.MyMethod();
But the Intellisence isn't showing it after I write the dot.
Upvotes: 4
Views: 4062
Reputation: 7126
Use a base controller
public abstract class BaseController : Controller
{
protected virtual void MyMethod()
{
// Do stuff
}
}
Then your controllers inherit your base controller
public class HomeController : BaseController
{
public ActionResult Index()
{
this.MyMethod();
return View();
}
}
Alternatively you could create a static helper class
public static class Helper
{
public static void MyMethod()
{
// Do stuff
}
}
public class HomeController
{
public ActionResult Index()
{
Helper.MyMethod()
return View();
}
}
Upvotes: 8
Reputation: 63962
Put it in a utility class and make it static. From your controllers all you need to do is something like:
Utility.SaveImage(...);
Upvotes: 10