MVC 3 get ActionResult of an action that is defined on a different controller

2.2k Views Asked by At

Problem:

What I need is something similar to @Html.RenderAction("action","controller") , but one that I can use from inside a different controller. This for example:

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

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

        return View();
   }
}

Progress:

I have begun to strip/reform the actual @Html.Action() method but it really has too many internal helper dependencies and I am thinking this shouldn't be that tough. What I have so far is:

    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");
    }

This works partially of course (minus the many shortcomings like area data tokens etc) but still there is no way other than reflection to get to the MyActionResult object.

Summary:

When inside a controller, what is a way to get an ActionResult from an action that is defined on a different controller, ?

Update:

More specifically, I am trying to use something like System.Web.Mvc.Html.ChildActionExtensions.ChildActionMvcHandler but one that doesnt execute, rather it returns the ActionResult

1

There are 1 best solutions below

3
On

Not sure why you want to return a ActionResult from a another controller. Possibly you could provide more details to understand us problem domain.

I think You could consider to use BaseController and declare a Static Method GetErrorDone with return results.

This method can be called from All Child Controllers.


OR 2nd Answer

Consider to just Redirect it to required Action using Controller.RedirectToAction

e.g. RedirectToAction("action name" "controller Name")