views:

39

answers:

2

Hey There

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?

+3  A: 

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(){}
Arnis L.
Insane... i was doing more or less the same, however, i did not inherit from ActionFilterAttribute.... THANX for the help, this is exactly what i needed
Dusty Roberts
Then mark it as answer.
Dialecticus
+1  A: 

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();
}
elder_george
thanx, this is also a neat work around. and i suppose that if you are using the enum elsewhere it makes more sense to do it this way.
Dusty Roberts