31

In ASP.NET MVC is there a way to enumerate the controllers through code and get their name?

example:

AccountController
HomeController
PersonController

would give me a list such as:

Account, Home, Person
Cœur
  • 37,241
  • 25
  • 195
  • 267
Denny Ferrassoli
  • 1,763
  • 3
  • 21
  • 40
  • 1
    ASP.Net MVC is already doing this, (i.e. it's how the controller names are discovered) if you could leverage the current implementation in MVC it would probably save you some time. – Chuck Conway Jul 20 '09 at 06:00
  • 1
    that is an excellent question here - how would I do that? – Roland Tepp Feb 25 '11 at 16:27

4 Answers4

44

Using Jon's suggestion of reflecting through the assembly, here is a snippet you may find useful:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;

public class MvcHelper
{
    private static List<Type> GetSubClasses<T>()
    {
        return Assembly.GetCallingAssembly().GetTypes().Where(
            type => type.IsSubclassOf(typeof(T))).ToList();
    }

    public List<string> GetControllerNames()
    {
        List<string> controllerNames = new List<string>();
        GetSubClasses<Controller>().ForEach(
            type => controllerNames.Add(type.Name));
        return controllerNames;
    }
}
Community
  • 1
  • 1
grenade
  • 31,451
  • 23
  • 97
  • 126
12

You can reflect through your assembly and find all classes which inherit from type System.Web.MVC.Controller. Here's some sample code that shows how you could do that:

http://mvcsitemap.codeplex.com/WorkItem/View.aspx?WorkItemId=1567

Jon Galloway
  • 52,327
  • 25
  • 125
  • 193
0

All who using this post better read this post before: using Assembly.GetCallingAssembly() not returns the calling assembly

The issue is that razor views are acting as independent dynamic assemblies and you don't get the desired assembly.

Yair

Community
  • 1
  • 1
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • 2
    I wouldnt call this from a view, I would pass the information from my viewmodel, doing so would mitigate your issue. – David McLean Aug 21 '12 at 09:30
-1

Create the property in every controller and then you get the name like this.

KuldipMCA
  • 3,079
  • 7
  • 28
  • 48
  • This is a good idea, if performance is an issue, then your way is probably the best approach (assuming you don't use reflection to discover the implementations). Otherwise, using reflection to grab the classname of the implementation is the easiest. – Chuck Conway Jul 20 '09 at 06:03
  • Rather than paste this into every controller, you can create your own controller class, and make all your controllers be one of this class, and the only thing you put into it that's not in the base controller class is this ViewName property – Brian White Aug 26 '14 at 16:39