【问题标题】:asp.net mvc custom attributesasp.net mvc 自定义属性
【发布时间】:2011-03-23 10:31:25
【问题描述】:

我正在尝试在 mvc 中创建一个自定义属性,以在视图中将其参数用作面包屑。

嗯,这是属性的代码

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class BreadCrumbAttribute : Attribute {

    public BreadCrumbAttribute(string title, string parent, string url) {
        this._title = title;
        this._parent = parent;
        this._url = url;
    }

    #region named parameters properties
    private string _title;
    public string Title {
        get { return _title; }
    }

    private string _url;
    public string Url {
        get { return _url; }
    }

    private string _parent;
    public string Parent {
        get { return _parent; }
    }
    #endregion

    #region positional parameters properties
    public string Comments { get; set; }
    #endregion

}

这是属性的调用

[BreadCrumbAttribute("tile", "parent name", "url")]
    public ActionResult Index() {
     //code goes here
     }

这是我想要获取值的一种方式。 (这是部分视图)

System.Reflection.MemberInfo inf = typeof(ProductsController);
object[] attributes;
attributes = inf.GetCustomAttributes(typeof(BreadCrumbAttribute), false);

foreach (Object attribute in attributes) {
    var bca = (BreadCrumbAttribute)attribute;
    Response.Write(string.Format("{0}><a href={1}>{2}</a>", bca.Parent, bca.Url, bca.Title));
}    

不幸的是,该属性没有以我实现它的方式被调用。虽然,如果我在 Class 中添加属性而不是 Action 方法,它会起作用。 我怎样才能让它工作?

谢谢

【问题讨论】:

    标签: asp.net asp.net-mvc custom-attributes


    【解决方案1】:

    问题是你使用反射来获取类的属性,所以它自然不包括在动作方法上定义的属性。

    要获得这些,您应该定义一个 ActionFilterAttribute,并且在 OnActionExecuting 或 OnActionExecuted 方法中,您可以使用 filterContext.ActionDescriptor.GetCustomAttributes() 方法 (MSDN description here)。

    请注意,使用此解决方案,您可能会拥有两种不同类型的属性:第一种是您编写的属性,用于定义面包屑。第二个是查看执行动作的属性并构建面包屑(并可能将其添加到 ViewModel 或将其粘贴在 HttpContext.Items 或其他东西中)。

    【讨论】:

    • 你的意思是 BreadCrubAttribute 将从 System.Attribute 扩展,我必须再创建一个属性,比如说 GetBreadCrumbAttribute 将从 ActionFilterAttribute 扩展?
    • 正确。 GetBreadCrumbAttribute 只存在于一个地方(假设您可以将它放在 BaseController 类中,所有其他控制器都从该类中下降)并且正如我所提到的,它将负责将找到的面包屑放在一起并将它们放在控制器的某个位置和/或视图可以检索它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-27
    • 2017-02-07
    相关资源
    最近更新 更多