C# 如何从 Mvc 中的控制器调用另一个控制器操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16870413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:00:25  来源:igfitidea点击:

How to call another controller Action From a controller in Mvc

c#asp.net-mvcasp.net-mvc-4

提问by user2156088

I need to call a controller B action FileUploadMsgView from Controller A and need to pass a parameter for it.

我需要从控制器 A 调用控制器 B 操作 FileUploadMsgView 并需要为其传递参数。

 Code---its not going to the controller B's FileUploadMsgView().
    In ControllerA
  private void Test()
    {

        try
        {//some codes here
            ViewBag.FileUploadMsg = "File uploaded successfully.";
            ViewBag.FileUploadFlag = "2";

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

     In ControllerB receiving part
  public ActionResult FileUploadMsgView(string FileUploadMsg)
    {
         return View();
    }

采纳答案by Tieson T.

Controllers are just classes - new one up and call the action method just like you would any other class member:

控制器只是类 - 一个新的类并像调用任何其他类成员一样调用 action 方法:

var result = new ControllerB().FileUploadMsgView("some string");

var result = new ControllerB().FileUploadMsgView("some string");

回答by Ed Chapel

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

您的示例看起来像伪代码。您需要返回以下结果RedirectToAction

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

回答by DLeh

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.

正如@mxmissile 在对已接受答案的评论中所说,您不应该更新控制器,因为它将缺少为 IoC 设置的依赖项,并且不会有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);

回答by cghore

This is exactly what I was looking for after finding that RedirectToAction()would not pass complex class objects.

这正是我在发现RedirectToAction()不会传递复杂类对象后所寻找的。

As an example, I want to call the IndexComparisonmethod in the LifeCycleEffectsResultscontroller and pass it a complex class object named model.

例如,我想调用控制器中的IndexComparison方法LifeCycleEffectsResults并将其传递给名为 model 的复杂类对象。

Here is the code that failed:

这是失败的代码:

return RedirectToAction("IndexComparison", "LifeCycleEffectsResults", model);

Worth noting is that Strings, integers, etc were surviving the trip to this controller method, but generic list objects were suffering from what was reminiscent of C memory leaks.

值得注意的是,字符串、整数等在这个控制器方法的旅程中幸存下来,但通用列表对象正在遭受让人想起 C 内存泄漏的问题。

As recommended above, here's the code I replaced it with:

如上所述,这是我将其替换为以下代码:

var controller = DependencyResolver.Current.GetService<LifeCycleEffectsResultsController>();

var result = controller.IndexComparison(model);
return result;

All is working as intended now. Thank you for leading the way.

现在一切都按预期工作。谢谢你带路。

回答by Nishanth Shaan

as @DLeh says Use rather

正如@DLeh 所说的那样使用

var controller = DependencyResolver.Current.GetService<ControllerB>();

But, giving the controller, a controlller context is important especially when you need to access the Userobject, Serverobject, or the HttpContextinside the 'child' controller.

但是,对于控制器,控制器上下文很重要,尤其是当您需要访问User对象、Server对象或HttpContext“子”控制器内部时。

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 Serveror the early metioned objects

否则你也可以使用 System.Web 访问当前上下文,访问Server或早期提及的对象

NB: i am targetting the framework version 4.6 (Mvc5)

注意:我的目标是框架版本 4.6 (Mvc5)

回答by David Castro

Let the resolver automatically do that.

让解析器自动执行此操作。

Inside A controller:

A控制器内部:

public class AController : ApiController
{
    private readonly BController _bController;

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

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

}

回答by David Castro

if the problem is to call. you can call it using this method.

如果问题是打电话。您可以使用此方法调用它。

yourController obj= new yourController();

obj.yourAction();

回答by AlexB

Dleh's answeris correct and explain how to get an instance of another controller without missing dependencies set up for IoC

Dleh 的回答是正确的,并解释了如何在不丢失为 IoC 设置的依赖项的情况下获取另一个控制器的实例

However, we now need to call the method from this other controller.
Full answer would be :

但是,我们现在需要从另一个控制器调用该方法。
完整的答案是:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

//Call your method
ActionInvoker.InvokeAction(controller.ControllerContext, "MethodNameFromControllerB_ToCall");

回答by Leonardo Wildt

If anyone is looking at how to do this in .net core I accomplished it by adding the controller in startup

如果有人正在研究如何在 .net core 中执行此操作,我通过在启动时添加控制器来完成它

services.AddTransient<MyControllerIwantToInject>();

Then Injecting it into the other controller

然后将其注入另一个控制器

public class controllerBeingInjectedInto : ControllerBase
{
    private readonly MyControllerIwantToInject _myControllerIwantToInject

     public controllerBeingInjectedInto(MyControllerIwantToInject myControllerIwantToInject)
{
       _myControllerIwantToInject = myControllerIwantToInject;
      }

Then just call it like so _myControllerIwantToInject.MyMethodINeed();

然后就这样称呼它 _myControllerIwantToInject.MyMethodINeed();

回答by Watth

I know it's old, but you can:

我知道它很旧,但你可以:

  • Create a service layer
  • Move method there
  • Call method in both controllers
  • 创建服务层
  • 在那里移动方法
  • 两个控制器中的调用方法