Reputation: 755
Can we call the Method of a controller from another controller in asp.net MVC?
Upvotes: 19
Views: 83221
Reputation: 1136
As controllers are just classes: Yes, we can do it. We can do it by some of the following ways:
By directly redirecting- return RedirectToAction("MethodName", "ControllerName");
By creating object - ControllerName objController=new ControllerName();
objController.methodName(parameters)
Upvotes: 1
Reputation: 11
Yes, you can call a method of another controller.
public ActionResult Index()
{
AccountController accountController = new AccountController {ControllerContext = ControllerContext};
return accountController.Index();
}
The controller is also a simple class. Only things are that its inheriting Controller Class. You can create an object of the controller, but it will not work for Routing if you want to redirect to another page.
Upvotes: 1
Reputation: 409
Try This.
var ctrl= new MyController();
ctrl.ControllerContext = ControllerContext;
//call action
return ctrl.Action();
Upvotes: 3
Reputation: 1108
You could also simply redirect straight to the method like so:
public class ThisController
{
public ActionResult Index()
{
return RedirectToAction("OtherMethod", "OtherController");
}
}
Upvotes: 21
Reputation: 76520
Well, there are number of ways to actually call an instance method on another controller or call a static method off that controller type:
public class ThisController {
public ActionResult Index() {
var other = new OtherController();
other.OtherMethod();
//OR
OtherController.OtherStaticMethod();
}
}
You could also redirect to to another controller, which makes more sense.
public class ThisController {
public ActionResult Index() {
return RedirectToRoute(new {controller = "Other", action = "OtherMethod"});
}
}
Or you could just refactor the common code into its own class, which makes even more sense.
public class OtherClass {
public void OtherMethod() {
//functionality
}
}
public class ThisController {
public ActionResult Index() {
var other = new OtherClass();
other.OtherMethod();
}
}
Upvotes: 9
Reputation:
Technically, yes. You can call a static method of a controller or initialize an instance of a controller to call its instance methods.
This, however, makes little sense. The methods of a controller are meant to be invoked by routing engine indirectly. If you feel the need to directly call an action method of another controller, it is a sign you need some redesign to do.
Upvotes: 13