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

后端 未结 6 1058
攒了一身酷
攒了一身酷 2021-02-07 10:45

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

相关标签:
6条回答
  • 2021-02-07 11:05

    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();
      }
    }
    
    0 讨论(0)
  • 2021-02-07 11:08

    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.

    0 讨论(0)
  • 2021-02-07 11:08

    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.

    0 讨论(0)
  • 2021-02-07 11:15

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

    public class ThisController 
    {
        public ActionResult Index() 
        {
           return RedirectToAction("OtherMethod", "OtherController");
        }
    }
    
    0 讨论(0)
  • 2021-02-07 11:19

    As controllers are just classes: Yes, we can do it. We can do it by some of the following ways:

    1. By directly redirecting- return RedirectToAction("MethodName", "ControllerName");

    2. By creating object - ControllerName objController=new ControllerName(); objController.methodName(parameters)

    0 讨论(0)
  • 2021-02-07 11:23

    Try This.

    var ctrl= new MyController();
    ctrl.ControllerContext = ControllerContext;
    //call action
    return ctrl.Action();
    
    0 讨论(0)
提交回复
热议问题