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

后端 未结 6 1270
攒了一身酷
攒了一身酷 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();
      }
    }
    

提交回复
热议问题