views:

75

answers:

2

I would like to define following attribute on MVC2:

public class BackAttribute : ActionFilterAttribute
{
   public BackAttribute(object routeDict)
   { // Set local route property according to routeDict }
}

Attribute would be used like this with anonymous type:

[Back(new { action = "Index", controller = "Home" })]
public ViewResult DoSome() ...

What I am trying to achieve is "back" attribute that defines where the "back" button in a page will lead to. Previous code doesn't compile because apparently it is a constant expression and you can't use anonymous type in that. How could I pass anonymous type to attribute or achieve one of the following calls:

[Back(new { action = "Index", controller = "Home"})]
[Back(action = "Index", controller = "Home")]

(Update) Or even

[Back(action = "Index", controller = "Home", id = "5", younameit = "dosome")]
A: 

You can't. As you have noticed, attribute parameters must be constants.

Thomas Levesque
+1  A: 

As has already been mentioned, you can't pass an anonymous type.

What you can do is this:

public class BackAttribute : ActionFilterAttribute
{
    public string Action { get; set; }
    public string Controller { get; set; }

    public BackAttribute() { }
}

Which will enable you to do this:

[Back(Action = "Index", Controller = "Home" )]
public ViewResult DoSomething() { //...

But you still won't be able to arbitrarily add other properties.

Bennor McCarthy
This is exactly what I have done now. As you said, it doesn't allow additional properties (like "id" and others). Could I use named parameters or pass a dictionary to the attribute?
Juho Rutila