stoic
stoic

Reputation: 4830

Custom Attributes and enumerators

I have an enum:

public enum Navigation
{
    Top = 0,
    Left = 2,
    Footer = 3
}

And i have a controller action:

public ActionResult Quotes()
{
    return View();
}

I would like to be able to decorate my action as follow:

[Navigation.Top]
public ActionResult Quotes()
{
    return View();
}

Any idea how this could be accomplished, i will probably have to create a custom attribute, but how do i incorporate this enum into it?

Upvotes: 0

Views: 227

Answers (2)

elder_george
elder_george

Reputation: 7879

Attribute annotations can only be created with classes derived from System.Attribute class.

So, it is not possible to use enum directly.

However it is possible to pass your enum value to the constructor of custom attribute. Like this:

enum Navigation 
{
    Top = 0,
    Left = 2,
    Footer = 3,
}
class NavigationAttribute: Attribute
{
    Navigation _nav;
    public NavigationAttribute(Navigation navigation){
        _nav = navigation;
    }
}
...
[Navigation(Navigation.Top)]
public ActionResult Quotes()
{
    return View();
}

Upvotes: 1

Arnis Lapsa
Arnis Lapsa

Reputation: 47607

One approach:

public static class Navigation{
  public class Top:ActionFilter /*any attribute*/{
   //magic
  }
  public class Left:ActionFilter{
   //magic
  }
}

[Navigation.Top]
public ActionResult Whatever(){}

If You do want to use enums, I'm afraid You won't be able to use them as attributes. But You can pass it to attribute as an argument. Something like this:

public class NavigationAttribute:Attribute{
  public Navigation Place {get;set;}
}

[Navigation(Place=Navigation.Top)]
public ActionResult Whatever(){}

Upvotes: 3

Related Questions