Is there a way to return an ActionResult from Controller B called from Controller A while providing a specific model to B?

前端 未结 4 713
耶瑟儿~
耶瑟儿~ 2021-01-19 01:51

Let\'s say I have a controller:

public BController : Controller
{
    public ActionResult Foo(FooViewModel vm)
    {
       ...
    }
 }

an

相关标签:
4条回答
  • 2021-01-19 02:07

    Have a look at this URL which explains how to pass parameters when redirecting from one action to another: http://jonkruger.com/blog/2009/04/06/aspnet-mvc-pass-parameters-when-redirecting-from-one-action-to-another/

    Hope this is helpful for you.

    0 讨论(0)
  • 2021-01-19 02:14

    You can do this:

    public AController : Controller
    {
         public ActionResult Bar(BarViewModel vm)
         {
              FooViewModel fooVm = MakeFooVM(vm);
              var bController = new BController();
              return bController.Foo(fooVm);
         }
    }
    
    0 讨论(0)
  • 2021-01-19 02:24

    An update to @WWC's answer that will help the target action be able to find the view it needs.

    public AController : Controller
    {
         public ActionResult Bar(BarViewModel vm)
         {
              FooViewModel fooVm = MakeFooVM(vm);
              var bController = new BController();
              var bControllerContext = new ControllerContext(this.ControllerContext.RequestContext, bController);
              // update route so action can find the (partial)view
              bControllerContext.RouteData.Values["controller"] = "B";
              bController.ControllerContext = bControllerContext;
              return bController.Foo(fooVm);
         }
    }
    
    0 讨论(0)
  • 2021-01-19 02:29

    Missing a step in the answer above. After you create the controller, you need to set the ControllerContext so that the controller's Request, Response, and HttpContext will be populated. Just creating the controller will result in null values for the controller's context settings.

    public AController : Controller
    {
         public ActionResult Bar(BarViewModel vm)
         {
              FooViewModel fooVm = MakeFooVM(vm);
              var bController = new BController();
              bController.ControllerContext = new ControllerContext(this.ControllerContext.RequestContext, bController);
              return bController.Foo(fooVm);
         }
    }
    

    Source: Get ActionResult of another controller-action?

    0 讨论(0)
提交回复
热议问题