[Asp.net] 在Model內的Properties加入CustomAttribute

  • 250
  • 0
[ExcelExport(Title = "營業點代碼", Column = 0)]  // <-就是我
public string StoreID { get; set; }

 

系統有一轉Excel的需求,

在想怎麼做會比較簡單,

最原始的方法就是一筆一筆新增(包含Title也是),

這也太麻煩了吧,

如果有很多支報表那不就要重複寫很多次嗎?

既然Model有可以在前方加Attribute產生ModelBinding的驗證功能

那就代表我或許也可以仿造類似的Attribute出來使用......

步驟如下:

Step 1: 宣告Attribute內容

    public class ExcelExportAttribute : Attribute
    {
        /// <summary>
        /// 欄位(Default)
        /// 預設為-1,沒有傳入時會依照Model內的排序來安排欄位
        /// </summary>
        private int _Column = -1;
        /// <summary>
        /// 標題
        /// </summary>
        public string Title { get; set; }
        /// <summary>
        /// 欄位
        /// </summary>
        public int Column { get; set; }
    }

Step 2: 在Model上加入Attribute

        [ExcelExport(Title = "營業點代碼", Column = 0)]
        public string StoreID { get; set; }

這樣就加完了,

不過要如何使用呢?

GetType()有提供取得Attribute的方法

使用方式如下:

Step 1: 取得Model的型別

// 我list的Type為 IEnumerable<T> ,是一串T型別的列舉值,所以程式可能會有些許差異
var srcType = list.GetType().UnderlyingSystemType.GetProperty("Item").PropertyType; // Model型別

Step 2: 取得Model的Properties

// 簡單來說就是Model內的內容,我的範例是Title跟Column
var srcProps = srcType.GetProperties();

Step 3: 從Property中取得Attribute

// 此處的prop已經是用Foreach由srcProps取得的單筆Property
// FirstOrDefault是因為可能會有多筆相同型別的Attribute,所以他會回傳一個IEnumerable
// 不過因為我每一筆Property只會放一筆此型別的Attribute,所以直接用FirstOrDefault取資料
var attr = prop.GetCustomAttributes(typeof(ExcelExportAttribute), true).FirstOrDefault();

Step 4: 取得設定值

// 強制轉型前請先由Step3的attr來判斷是否有正確的Attribute,否則會跳出Exception
var title = ((ExcelExportAttribute)attr).Title;
var column = ((ExcelExportAttribute)attr).Column;

這樣就可以取得Model的CustomAttribute內所設定的資料了

 

參考文章:

http://www.dotnetcurry.com/aspnet-mvc/687/create-custom-attributes-meta-data

http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html

http://stackoverflow.com/questions/6205176/finding-custom-attributes-on-view-model-properties-when-model-binding

Write By Charley Chang 


新手發文,若有錯誤還請指教,
歡迎留言或Mail✉給我

創用 CC 授權條款


本著作係採用創用 CC 姓名標示-非商業性-相同方式分享 4.0 國際 授權條款授權.