Reputation: 31
I am new to MVC ASP.NET and needed to call an action from one controller in an action of another controller. There I created object of controller and called my required action as below,
controllerOne co = new controllerOne();
co.requiredFunction();
but one of my senior advised me to not use this approach, which kills the MVC pattern use its given ActionInvoker.InvokeAction()
function to call function of other controller and I am using now as below,
public class HomeController : Controller
{
this.ActionInvoker.InvokeAction(new System.Web.Mvc.ControllerContext(
this.ControllerContext.RequestContext, new controllerOne()),
"requiredAction");
}
This works fine, but I don't know if the way I am using ActionInvoker.InvokeAction()
is correct. I searched to find any example but I could find any.
So my question is: Am I using it correctly?
Upvotes: 3
Views: 2838
Reputation: 21
use this
var ctrl= new MyController();
ctrl.ControllerContext = ControllerContext;
//call action
return ctrl.Action();
Upvotes: 1
Reputation: 20674
To do this many people would create a service that encapsulates this requiredFunction
and inject the service through it's interface into both controllers
Upvotes: 2