2011-03-23 7 views
0

mvc에서 사용자 정의 속성을 작성하여 뷰의 매개 변수를 breadCrumb로 사용하려고합니다.asp.net 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)); 
}  

불행히도, 속성은 구현 방법으로 전화를받지 못했습니다. 하지만, Action 메소드 대신 Class에 속성을 추가하면 효과적입니다. 어떻게 작동시킬 수 있습니까?

감사

답변

2

문제는 당신이 자연스럽게는 액션 메소드에 정의 된 속성을 포함하지 않는 클래스의 속성을 얻기 위해 반사를 사용하는 것입니다.

이들을 얻으려면 ActionFilterAttribute를 정의하고 OnActionExecuting 또는 OnActionExecuted 메서드에서 filterContext.ActionDescriptor.GetCustomAttributes() 메서드 (MSDN description here)를 사용할 수 있습니다.

이 솔루션을 사용하면 다음과 같은 두 가지 유형의 속성을 가질 수 있습니다. 첫 번째 것은 작성한 것으로, 빵 부스러기를 정의합니다. 두 번째는 실행중인 액션의 속성을보고 빵 부스러기를 만듭니다 (그리고 아마도 ViewModel에 추가하거나 HttpContext.Items 또는 다른 것으로 붙여 넣기 것입니다).

+0

당신은 BreadCrubAttribute가 System.Attribute에서 확장되고 하나의 속성을 추가해야한다는 것을 의미합니다. ActionFilterAttribute에서 확장 될 GetBreadCrumbAttribute를 말할 수 있습니까? – StrouMfios

+0

수정하십시오. GetBreadCrumbAttribute는 한 곳에서만 존재할 것입니다 (다른 모든 컨트롤러가 내려지는 BaseController 클래스에 놓을 수 있다고 가정 할 때). 내가 언급했듯이, 컨트롤러가 발견 한 빵 부스러기를 함께 배치하고 컨트롤러에 배치해야 할 책임이 있습니다 및/또는 뷰가 그들을 검색 할 수 있습니다. –