Sirwan Afifi
Sirwan Afifi

Reputation: 10824

How to set metadata for controller and action methods?

I'm using this code for displaying all controllers name with action methods:

public ActionResult GetAllControllers()
        {
            var controllers = typeof (MvcApplication).Assembly.GetTypes().Where(typeof (IController).IsAssignableFrom);
            return View(controllers.ToList());
        }

View:

<ul id="treeView">
    @foreach (var item in Model)
    {
            <li>
                @item.Name
                <ul>
                    @foreach (var action in item.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(method => typeof(ActionResult).IsAssignableFrom(method.ReturnType)))
                    {
                        <li>@action.Name</li>
                    }
                </ul>
            </li>
    }

</ul>

The result is look like this:

HomeController
     Index
     About
MainController
     Index
     Create
     Edit
     Delete
...

Now my question is that: Is there any way to set a name for controller and action method as display result? For example something like this:

[SetName("MainPage")]
public class HomeController : Controller
{
    [SetName("ProductList")]
    public ActionResult Index()
    {
        //
    }
    // other action methods
}

So in this case the result for displaying controllers name and action methods would be:

MainPage
   ProductList
... 

Upvotes: 1

Views: 573

Answers (1)

Reza
Reza

Reputation: 19933

Create a new attribute class, then read the attributes by GetCustomAttributes() method on Property and Class

Upvotes: 1

Related Questions