Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call another controller Action From a controller in Mvc

People also ask

How do I redirect to another controller?

In this blog you will learn how to Redirect from One Controller Action to Another. Step1: Create an ASP.net MVC project. Choose ASP.Net MVC project from template and Press Next, then name the empty project as RoutingExample and click ok. Step 2: Add two controllers.

How can we call a controller from another view in MVC?

Redirection is very easy, you just call controller and then action in that as above suggested. There is option available to pass parameter too. return RedirectToAction("Tests", new { ID = model.ID, projectName = model. ProjectName });


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);

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");


Your sample looks like psuedo code. You need to return the result of RedirectToAction:

return RedirectToAction("B", 
                        "FileUploadMsgView",
                        new { FileUploadMsg = "File uploaded successfully" });

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)


Let the resolver automatically do that.

Inside A controller:

public class AController : ApiController
{
    private readonly BController _bController;

    public AController(
    BController bController)
    {
        _bController = bController;
    }

    public httpMethod{
    var result =  _bController.OtherMethodBController(parameters);
    ....
    }

}