繁体   English   中英

ASP.NET | 从 MVC 中的 controller 调用另一个控制器的操作

[英]ASP.NET | Call another controller's action from a controller in MVC

我正在考虑一个与前段时间提出的问题非常相似的场景: How to call another controller Action From a controller in Mvc

在我想到的场景中,controller B 会返回一个部分视图,我想将其合并到 Home controller 返回的 ViewResult 中,因此代码可能如下所示:

public class Home
{
    public ActionResult Index()
    {
        ActionResult partialViewFromCtrl_B = RedirectToAction(actionName: "SomeAction", 
                                                              controllerName: "Controller_B");
        
        // The returned view should include the partial view `partialViewFromCtrl_B`
        return View();
    }
}

public class Controller_B
{
    public ActionResult SomeAction()
    {
        // Do some stuff

        return PartialView(viewName: "_SomeAction", model: someModel);
    }
}

有没有办法把controller B返回的部分视图合并到Home controller返回的视图中? 如果可能的话,我希望将为 controller B 定义的逻辑和视图与 Home controller 分开,而不是将所有内容合并到 Home controller 中。

非常感激你的帮助!


编辑:如果 Home controller 的 Index.cshtml 看起来像这样,我的场景的一种可能解决方案可能是

@model SomeModelType
...
@Html.Partial(partialview: "~/Controller_B/_SomeAction", model: Model)
...

Home controller 的Index()操作将如下所示:

public ActionResult Index()
    {
        // Get the model from Controller_B instead of the partial view
        SomeModelType someModelFromCtrl_B = new Controller_B().returnSomeModel();
        
        return View(someModelFromCtrl_B);
    }

然而,这对我来说似乎不是最好的方法。

因此,如果可能的话,我想在 Home controller 的操作方法中组合 Home controller 的局部视图Controller_B/_SomeActionIndex视图(如果可能的话)。

通过发布的代码我无法理解你想要返回什么。 根据您的小代码,我认为您打算在 PartialView 中返回索引值。 看看下面的代码:

public class Home
{
  public ActionResult Index()
  {
    if(//cond){
        // Do some stuff
        return PartialView(viewName: "_SomeAction", model: someModel);          
    }       
    else{
        ActionResult partialViewFromCtrl_B = RedirectToAction(actionName: "SomeAction", 
                                                          controllerName: "Controller_B");        
        // The returned view should include the partial view `partialViewFromCtrl_B`
        return View("Index");           
    }       
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM