views:

420

answers:

3

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

Thanks!

A: 

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

KuldipMCA
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
that's right thanks for sharing knowledge.
KuldipMCA
+3  A: 

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
I ended up using this approach. I also cached the list since it would be reused often. Thanks
DennyDotNet
+3  A: 

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;
    }
}
grenade