如何使用表中列的名称填充DropDownList

时间:2015-02-10 13:47:56

标签: c# model-view-controller drop-down-menu entity

早上好

我有一个名为 AGG_TREE 的表包含以下4列:

“COL_AGG”,“PARENT_CODE”,“因素”和“DATE_CREATED”

我做了什么:使用列的名称显示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();
    }

感谢您的帮助

2 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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'的定义,并且没有扩展方法'CustomAttributes'接受类型'System.Reflection.PropertyInfo'的第一个参数可以找到(你是吗?)缺少using指令或程序集引用?)C:\ ADA Projets \ DecisionPortal \ Web \ Controllers \ IrhRegroupementController.cs 28 32 WebPortal