简体   繁体   English

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

[英]C#: Anonymous type as a parameter to ActionFilterAttribute

I would like to define following attribute on MVC2: 我想在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")]

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. 但是您仍然无法任意添加其他属性。

You can't. 你不能 As you have noticed, attribute parameters must be constants. 您已经注意到,属性参数必须是常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM