从DataTable填充MVC Webgrid

时间:2011-05-29 15:24:27

标签: asp.net-mvc-3 webgrid

我正在尝试使用DataTable填充MVC Webgrid,DataTable是在后面的代码中构建的,然后使用AsEnumerable()扩展方法进行枚举。

但是,当我调用GetHtml方法时,输出不是我所期望的,它包含两列HasErrors和RowError,而没有我定义的列。

我错过了什么吗?

        DataTable table = new DataTable();
        table.Columns.Add("I/Dia");

        foreach (var item in Variations.Where(item => !table.Columns.Contains(item.CrossSectionalDiameter)))
        {
            table.Columns.Add(item.CrossSectionalDiameter);
        }

        foreach (var item in Variations)
        {
            var r = table.Rows.Add();
            r["I/Dia"] = item.InternalDiameter;
            r[item.CrossSectionalDiameter] = item.Price;
        }

        return table.AsEnumerable();

2 个答案:

答案 0 :(得分:11)

我有类似的问题。最后根据你的评论做一些解决。

        var result = new List<dynamic>();
        foreach (DataRow row in table.Rows)
        {
            var obj = (IDictionary<string, object>)new ExpandoObject();
            foreach (DataColumn col in table.Columns)
            {
                obj.Add(col.ColumnName, row[col.ColumnName]);
            }
            result.Add(obj);
        }
        var grid = new WebGrid(result)

答案 1 :(得分:0)

将数据转换为列表

    #region "Convert DataTable to List<dynamic>"

    public List<dynamic> ToDynamicList(DataTable dt)
    {
        List<string> cols = (dt.Columns.Cast<DataColumn>()).Select(column => column.ColumnName).ToList();
        return ToDynamicList(ToDictionary(dt), getNewObject(cols));
    }
    public List<Dictionary<string, object>> ToDictionary(DataTable dt)
    {
        var columns = dt.Columns.Cast<DataColumn>();
        var Temp = dt.AsEnumerable().Select(dataRow => columns.Select(column =>
                             new { Column = column.ColumnName, Value = dataRow[column] })
                         .ToDictionary(data => data.Column, data => data.Value)).ToList();
        return Temp.ToList();
    }
    public List<dynamic> ToDynamicList(List<Dictionary<string, object>> list, Type TypeObj)
    {
        dynamic temp = new List<dynamic>();
        foreach (Dictionary<string, object> step in list)
        {
            object Obj = Activator.CreateInstance(TypeObj);
            PropertyInfo[] properties = Obj.GetType().GetProperties();
            Dictionary<string, object> DictList = (Dictionary<string, object>)step;
            foreach (KeyValuePair<string, object> keyValuePair in DictList)
            {
                foreach (PropertyInfo property in properties)
                {
                    if (property.Name == keyValuePair.Key)
                    {
                        property.SetValue(Obj, keyValuePair.Value.ToString(), null);
                        break;
                    }
                }
            }
            temp.Add(Obj);
        }
        return temp;
    }       
    private Type getNewObject(List<string> list)
    {
        AssemblyName assemblyName = new AssemblyName();
        assemblyName.Name = "tmpAssembly";
        AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
        ModuleBuilder module = assemblyBuilder.DefineDynamicModule("tmpModule");
        TypeBuilder typeBuilder = module.DefineType("WebgridRowCellCollection", TypeAttributes.Public);
        foreach (string step in list)
        {
            string propertyName = step;
            FieldBuilder field = typeBuilder.DefineField(propertyName, typeof(string), FieldAttributes.Public);
            PropertyBuilder property = typeBuilder.DefineProperty(propertyName, System.Reflection.PropertyAttributes.None, typeof(string), new Type[] { typeof(string) });
            MethodAttributes GetSetAttr = MethodAttributes.Public | MethodAttributes.HideBySig;
            MethodBuilder currGetPropMthdBldr = typeBuilder.DefineMethod("get_value", GetSetAttr, typeof(string), Type.EmptyTypes);
            ILGenerator currGetIL = currGetPropMthdBldr.GetILGenerator();
            currGetIL.Emit(OpCodes.Ldarg_0);
            currGetIL.Emit(OpCodes.Ldfld, field);
            currGetIL.Emit(OpCodes.Ret);
            MethodBuilder currSetPropMthdBldr = typeBuilder.DefineMethod("set_value", GetSetAttr, null, new Type[] { typeof(string) });
            ILGenerator currSetIL = currSetPropMthdBldr.GetILGenerator();
            currSetIL.Emit(OpCodes.Ldarg_0);
            currSetIL.Emit(OpCodes.Ldarg_1);
            currSetIL.Emit(OpCodes.Stfld, field);
            currSetIL.Emit(OpCodes.Ret);
            property.SetGetMethod(currGetPropMthdBldr);
            property.SetSetMethod(currSetPropMthdBldr);
        }
        Type obj = typeBuilder.CreateType();
        return obj;
    }

    #endregion