How could I write code to get all the action names from a controller in asp.net MVC?
I want to automatically list all the action names from a controller.
Does anyone know how to do this?
Many thanks.
I've been wrestling with this question for a while now, and I believe I've come up with a solution that should work most of the time. It involves getting a ControllerDescriptor for the controller in question, and then checking each ActionDescriptor returned by ControllerDescriptor.GetCanonicalActions().
I ended up making an action that returned a partial view in my controller, but I think it's fairly easy to figure out what's going on so feel free to take the code and change it around to your needs.
[ChildActionOnly]
public ActionResult Navigation()
{
// List of links
List<string> NavItems = new List<string>();
// Get a descriptor of this controller
ReflectedControllerDescriptor controllerDesc = new ReflectedControllerDescriptor(this.GetType());
// Look at each action in the controller
foreach (ActionDescriptor action in controllerDesc.GetCanonicalActions())
{
bool validAction = true;
// Get any attributes (filters) on the action
object[] attributes = action.GetCustomAttributes(false);
// Look at each attribute
foreach (object filter in attributes)
{
// Can we navigate to the action?
if (filter is HttpPostAttribute || filter is ChildActionOnlyAttribute)
{
validAction = false;
break;
}
}
// Add the action to the list if it's "valid"
if (validAction)
NavItems.Add(action.ActionName);
}
return PartialView(NavItems);
}
There are probably more filters to be looking out for, but for now this suits my needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With