views:

25

answers:

2

I want to list all the existing controllers from within master page.

For example:

In my Controller folder I have:

  1. HomeController with actions Index, etc...
  2. ProductController with actions Index, Details, etc...
  3. ServiceController with actions Index, Edit, etc...
  4. SomethingController with actions Index, Update, etc...
  5. etc

From within my Site.master, I want to list all of these Action controller dynamically.

+1  A: 

From within my Site.master, I want to list all of these Action controller dynamically.

Views are not supposed to pull data. They are supposed to show data/model passed by a controller. So inside your controller you could use reflection to list all the types deriving from Controller and pass them to the view for rendering. Another possibility is to have an HTML helper that will do the job.

Darin Dimitrov
+2  A: 

Whilst I totally agree with @Darin's response, here is a relatively simple way to do what you're asking, using ViewData.

Regarding the actual logic for enumerating all controllers. I won't add that here as this is a reasonable way of doing it, that I probably couldn't improve upon.

You could do something using ViewData to store all of your controllers and actions dynamically from OnActionExecuting. You'd have to create a new controller from which all of your other controllers would inherit.

So, for example, with your ProductController:

public class ProductController : MyCustomController
{
  ...
}

...

public class MyCustomController : Controller
{
  protected override void OnActionExecuting(ActionExecutingContext filterContext)
  {
    base.OnActionExecuting(filterContext);

    //Some logic (not written) to reflect each of the controllers and actions. Probably something utilising IGrouping.
    var controllersActions = GetControllersActions();

    //Drop your collection into the ControllersActions.
    filterContext.Controller.ViewData.Add("ControllersActions", controllersActions);
  }
}

In your master page...

<% var controllersActions = ViewData["ControllersActions"]; %>

... outputting your controllers/actions ...
Dan Atkinson