views:

792

answers:

3

How can I get the actual "Main-Controller" in a RenderAction?

Example:

MyRoute:

{controller}/{action}

My url my be: pages/someaction tours/someaction ...

In my Site.Master I make a RenderAction:

<% Html.RenderAction("Index", "BreadCrumb"); %>

My BreadCrumbController Action looks like this:

public ActionResult Index(string controller)
{

}

The strings controller contains "BreadCrumb" (which is comprehensible because actually I am in BreadCrumbController).

What's the best way to get the "real" controller (e.g. pages or tours).

A: 

What do you mean with "real" controller? Your action points to one controller.
Do you mean the previous controller? So: the controller that was used to render your view where your link was created that points to your breadcrumbcontroller?
Unless you add the name of that controller to the link as a parameter, there is no way to get to that.

borisCallens
+1  A: 

Could you pass it as a parameter to the controller?

--Site.master--

 <% Html.RenderAction("Index", "BreadCrumb"
                      new { controller = ViewData["controller"] }); %>

--BreadCrumbController.cs--

  public ActionResult Index(string controller)
  {

  }

--ToursController.cs--

 public ActionResult SomeAction(...)
 {
      // ....
      ViewData["controller"] = "Tours"  
      // You could parse the Controller type name from:
      // this.ControllerContext.Controller.GetType().Name
      // ....
 }
GuyIncognito
That's what I do, only a bit differently to the way you do it:<% Html.RenderAction("TopLevelMenu", "Navigation", new { currentController = ViewContext.RouteData.Values["controller"].ToString(), currentAction = ViewContext.RouteData.Values["action"].ToString() }); %>
RichardOD
+3  A: 

Parent view/controller context

If you use MVC 2 RC (don't know about previous releases) you can get to parent controller via view's context, where you will find a property called:

ViewContext ParentActionViewContext;

which is parent view's context and also has a reference to its controller that initiated view rendering...

Routing

It seems to me (from your question) that you have requests with an arbitrary number of route segments... In this case you have two options:

  1. Define your route with a greedy parameter where actions in this case will catch all actions in your request URL

    {controller}/{*actions}

  2. Create a custom Route class that will handle your custom route requirements and populate RouteData as needed.

the second one requires a bit more work and routing knowledge but it will help you gain some more knowledge about Asp.net MVC routing. I've done it in the past and it was a valuable lesson. And also an elegant way of handling my custom route requirements.

Robert Koritnik