2015-02-10 87 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