asp.net mvc custom attributes

烈酒焚心 提交于 2019-12-12 10:24:07

问题


I am trying to create a custom attribute in mvc to use it's parameters in a view as breadCrumb.

well, this is the code of the attribute

[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

}

this is the call of the attribute

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

this is a way of how I'd like to get the values. (this is a partial view)

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));
}    

Unfortunately, the attribute didn't get call with the way I implement it. Although, If I add the attribute in Class instead of an Action method it worked. How could I make it work?

Thanks


回答1:


The problem is that you are using reflection to get the attributes for the class, so naturally it does not include attributes defined on the action method.

To get those, you should define an ActionFilterAttribute, and in the OnActionExecuting or OnActionExecuted method, you can use filterContext.ActionDescriptor.GetCustomAttributes() method (MSDN description here).

Note that with this solution, you will likely have two different types of attributes: The first one is the one you wrote, to define the breadcrumbs. The second is the one that looks at the attributes on the executing action and builds up the breadcrumb (and presumably adds it to the ViewModel or sticks it in HttpContext.Items or something).



来源:https://stackoverflow.com/questions/5403856/asp-net-mvc-custom-attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!