MVC 3获取在不同控制器上定义的动作的ActionResult

时间:2012-05-30 12:30:48

标签: asp.net-mvc reflection asp.net-mvc-routing controller-factory

问题:

我需要的东西类似于@ Html.RenderAction(“action”,“controller”),但我可以在不同的控制器中使用。例如:

public class FirstController : Controller
{
   public ActionResult GetErDone()
   {
        return View();
   }
}

public class SecondController : Controller
{
   public ActionResult Index()
   {
        ActionResult coolResult = 
               Helper.GetActionResult("GetErDone", "FirstController");

        return View();
   }
}

进度:

我已经开始剥离/改造实际的@ Html.Action()方法,但它确实有太多的内部帮助依赖项,我认为这不应该那么难。到目前为止我所拥有的是:

    private void TestCreateActionFromDifferentController(RouteValueDictionary routeValues, string controllerName, string actionName)
    {
        var httpContext = this.HttpContext;
        var routeData = this.RouteData;
        routeData.Values["action"] = (object)actionName;

        if (!string.IsNullOrEmpty(controllerName))
            routeData.Values["controller"] = (object)controllerName;

        IController myController = ControllerBuilder.Current.GetControllerFactory().CreateController(new RequestContext(httpContext, routeData) , "staticpages");
    }

当然这部分工作(减去区域数据令牌等许多缺点)但除了反射之外别无法进入MyActionResult对象。

要点:

当在控制器内部时,从不同控制器上定义的动作获取ActionResult的方法是什么?

更新

更具体地说,我试图使用像System.Web.Mvc.Html.ChildActionExtensions.ChildActionMvcHandler这样的东西但不执行,而是返回ActionResult

1 个答案:

答案 0 :(得分:1)

不确定为什么要从另一个ActionResult返回controller。可能您可以提供更多细节来了解我们的问题域。

我认为您可以考虑使用BaseController并使用返回结果声明静态方法GetErrorDone

可以从All Child Controllers调用此方法。


  

或第二回答

考虑使用 Controller.RedirectToAction

将其重定向到所需的操作
e.g. RedirectToAction("action name" "controller Name")