C#:匿名类型作为ActionFilterAttribute的参数

时间:2010-08-19 09:25:35

标签: c# asp.net-mvc-2 c#-4.0

我想在MVC2上定义以下属性:

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

属性将像匿名类型一样使用:

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

我想要实现的是“后退”属性,它定义了页面中“后退”按钮的位置。以前的代码不能编译,因为它显然是一个常量表达式,你不能使用匿名类型。我怎样才能将匿名类型传递给属性或实现以下调用之一:

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

(更新)甚至

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

2 个答案:

答案 0 :(得分:1)

如前所述,您无法传递匿名类型。

你可以做的是:

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

    public BackAttribute() { }
}

这将使您能够这样做:

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

但你仍然无法随意添加其他属性。

答案 1 :(得分:0)

你做不到。如您所知,属性参数必须是常量。