使用反射,取得要篩選排序的欄位或指定欄位的數值

  • 3369
  • 0
  • 2013-09-15

摘要:使用反射,取得要篩選排序的欄位或指定欄位的數值

1. C#裡面,依照條件選擇要撈取或排序的欄位:
public ActionResult Links(string id, string sort)
{
        var _db = new TestEntities();
        // 篩選
        string colIsName;
        string colOnName;
        SortBy sortBy = (SortBy)Enum.Parse(typeof(SortBy), sort); // 字串轉成Enum
        switch (sortBy)
        {
                case SortBy.Viewd:
                    colIsName = "IsViewed";
                    colOnName = "ViewedOn";
                    break;
                case SortBy.Like:
                    colIsName = "IsLiked";
                    colOnName = "LikedOn";
                    break;
        }
        System.Reflection.PropertyInfo propIs = typeof(UserLinkVideo).GetProperty(colIsName);
        System.Reflection.PropertyInfo propOn = typeof(UserLinkVideo).GetProperty(colOnName);
        ViewBag.DateOnCol = colOnName; // 給在View要反射欄位時使用,如果需要的話
        // 撈取
        var links = _db.UserLinkVideo.Where(x => x.VideoId == id && ((bool)propIs.GetValue(x, null))).OrderByDescending(x => propOn.GetValue(x, null));
        return View(links);
}
2. View裡面,依照條件取得巢狀迴圈的值:
@{
// 要使用的欄位,這裡的【ModelTypeName】為傳入該ViewModel型別名稱
System.Reflection.PropertyInfo prop = typeof(UserLinkVideo).GetProperty(ViewBag.DateOnCol);
string displayText;
}
@foreach (var item in Model)
{
    displayText = item.GetType().GetProperty(prop.Name).GetValue(item, null).ToString();
}