Can we call the Method of a controller from another controller in asp.net MVC?

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

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.


You could also simply redirect straight to the method like so:

public class ThisController 
{
    public ActionResult Index() 
    {
       return RedirectToAction("OtherMethod", "OtherController");
    }
}

Tags:

Asp.Net Mvc