2015-02-10 31 views
1

早安如何填充列的名稱一個DropDownList在表

我有一個表稱爲AGG_TREE包含以下4個列:

「COL_AGG」,「PARENT_CODE」,「因子」和‘DATE_CREATED’

我做了什麼:dispayed一個DropDownList與列的名字,當我選擇列的名字,我會顯示在視圖中它的數據

這是我可以做的:

AGG_TREEEntities db = new AGG_TREEEntities(); 

     var query = (from discs in db.AGG_TREE 

        select [ the names of the columns ??? ].ToList(); 

     List<string> nameOfMycolumns = new List<string>(); 
     foreach (var item in query) 
     { 
      nameOfMycolumns .Add(item.[the names of the columns ???]); 
     } 
     ViewBag.NameOfMycolumns = nameOfMycolumns ; 
     return View(); 
    } 

謝謝您的幫助

回答

0

您可以使用反射在這裏:

Type type = typeof(AGG_TREE); //that would be the name of the class 
    List<string> nameOfMycolumns = type.GetProperties() 
      .Where(
       prop => prop.GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false).Any() && 
       !prop.GetCustomAttributes(typeof(EdmRelationshipNavigationPropertyAttribute), false).Any()) 
      .Select(prop => prop.Name).ToList(); 
ViewBag.NameOfMycolumns = nameOfMycolumns; 
return View(); 

並在視圖使用:

@Html.DropDownList("yourProperty", new SelectList(ViewBag.NameOfMycolumns)) 
+0

它工作得很好。謝謝 – Jeremy 2015-02-25 08:46:35

+0

@Jeremy如果它有效,請考慮接受答案(答案左側的校驗符號)。沒有必要說謝謝......它給了我們兩個小小的聲譽,而且這個論壇的其他用戶可以更好地看到問題已經解決,因此它對我們所有人都有好處。但不用說,你可以=) – 2015-02-25 09:07:03

0

謝謝你回答我

問題:我的課程名稱必須與我的表名稱完全相同?

我的類:

public class AGG_Tree 
{ 
    public string COL_AGG{ get; set; } 
    public string CODE { get; set; } 
    public int FACTOR { get; set; } 
    public DateTime DATE_CREATED { get; set; } 
} 

和我的控制器:

public ActionResult Index() 
    { 
     Type type = typeof(AGG_Tree); //that would be the name of the class 

     List<string> nameOfMycolumns = type.GetProperties() 
      .Where(
       prop => prop.CustomAttributes.Any(attr => attr.AttributeType == typeof(EdmScalarPropertyAttribute)) && 
       !prop.CustomAttributes.Any(attr => attr.AttributeType == typeof(EdmRelationshipNavigationPropertyAttribute))) 
      .Select(prop => prop.Name).ToList(); 
     ViewBag.NameOfMycolumns = nameOfMycolumns; 

     return View(); 

    } 

錯誤:

錯誤2 'System.Reflection.PropertyInfo' 不包含 'CustomAttributes' 的定義。並且沒有找到接受'System.Reflection.PropertyInfo'類型的第一個參數的擴展方法'CustomAttributes'可以找到(你是否缺少using指令或彙編)C:\ ADA Projets \ DecisionPortal \ Web \ Controllers \ IrhRegroupementController.cs 28 32 WebPortal

+0

對不起,我沒有理解你的問題 – Jeremy 2015-02-10 15:10:15

+0

我用.net框架4.0 – Jeremy 2015-02-10 15:17:07

+0

編輯答案...在4.0和更早版本中沒有屬性CustomAttributes。 – 2015-02-10 15:20:33

相關問題