Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.net MVC: get "Main-Controller" in RenderAction

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).

like image 408
chbu Avatar asked May 15 '09 08:05

chbu


2 Answers

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.

like image 157
Robert Koritnik Avatar answered Sep 28 '22 04:09

Robert Koritnik


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
      // ....
 }
like image 44
GuyIncognito Avatar answered Sep 28 '22 03:09

GuyIncognito