我们可以从asp.net MVC中的另一个控制器调用控制器的方法吗?

SAH*_*GLA 14 asp.net-mvc

我们可以从asp.net MVC中的另一个控制器调用控制器的方法吗?

Nic*_*sao 19

你也可以简单地直接重定向到这样的方法:

public class ThisController 
{
    public ActionResult Index() 
    {
       return RedirectToAction("OtherMethod", "OtherController");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这是重定向,而不是呼叫。OP 要求打电话。 (5认同)

小智 11

从技术上讲,是的.您可以调用控制器的静态方法或初始化控制器的实例以调用其实例方法.

然而,这没有多大意义.控制器的方法意味着间接地由路由引擎调用.如果您觉得需要直接调用另一个控制器的动作方法,那么您需要进行一些重新设计.

  • 同意.最好返回一个`RedirectToRouteResult`,而不是只调用另一个控制器. (2认同)

Igo*_*aka 7

好吧,有很多方法可以在另一个控制器上实际调用实例方法,或者从该控制器类型调用静态方法:

public class ThisController {
  public ActionResult Index() {
    var other = new OtherController();
    other.OtherMethod();
    //OR
    OtherController.OtherStaticMethod();
  }
}
Run Code Online (Sandbox Code Playgroud)

您也可以重定向到另一个控制器,这更有意义.

public class ThisController {
  public ActionResult Index() {
    return RedirectToRoute(new {controller = "Other", action = "OtherMethod"});
  }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以将公共代码重构为自己的类,这更有意义.

public class OtherClass {
  public void OtherMethod() {
    //functionality
  }
}

public class ThisController {
  public ActionResult Index() {
    var other = new OtherClass();
    other.OtherMethod();
  }
}
Run Code Online (Sandbox Code Playgroud)