How to call another controller Action From a controller in Mvc
as @DLeh says Use rather
var controller = DependencyResolver.Current.GetService<ControllerB>();
But, giving the controller, a controlller context is important especially when you need to access the User
object, Server
object, or the HttpContext
inside the 'child' controller.
I have added a line of code:
controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);
or else you could have used System.Web to acces the current context too, to access Server
or the early metioned objects
NB: i am targetting the framework version 4.6 (Mvc5)
Controllers are just classes - new one up and call the action method just like you would any other class member:
var result = new ControllerB().FileUploadMsgView("some string");
As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext
.
Instead, you should get an instance of your controller like this:
var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);
Your sample looks like psuedo code. You need to return the result of RedirectToAction
:
return RedirectToAction("B",
"FileUploadMsgView",
new { FileUploadMsg = "File uploaded successfully" });