无法在LINQ方法下施放类型的对象
我在下面的代码行号(var ColumnNames =
)中获得以下错误。
`System.InvalidCastException: 'Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.'`
Javscript控制台中的代码
public JsonResult SaveData(List<object> customers)
{
DataTable dt = new DataTable();
var columnNames = ((Dictionary<string, object>)customers[0]).Select(x => x.Key).ToList();
for (int i = 0; i < columnNames.Count(); i++)
{
dt.Columns.Add(columnNames[i]);
}
foreach (Dictionary<string, object> customer in customers)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < columnNames.Count(); i++)
{
dr[columnNames[i]] = customer[columnNames[i]];
}
dt.Rows.Add(dr);
}
return Json('1');
}
显示传递数据
0 : {Id: "1", Name: "abc", Country: "uk", __rowNum__: 1}
1: {Id: "2", Name: "kala", Country: "us", __rowNum__: 2}
2: {Id: "3", Name: "Has", Country: "IN", __rowNum__: 3}
I am getting following error in below code line No (var columnNames =
).
`System.InvalidCastException: 'Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]'.'`
Code
public JsonResult SaveData(List<object> customers)
{
DataTable dt = new DataTable();
var columnNames = ((Dictionary<string, object>)customers[0]).Select(x => x.Key).ToList();
for (int i = 0; i < columnNames.Count(); i++)
{
dt.Columns.Add(columnNames[i]);
}
foreach (Dictionary<string, object> customer in customers)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < columnNames.Count(); i++)
{
dr[columnNames[i]] = customer[columnNames[i]];
}
dt.Rows.Add(dr);
}
return Json('1');
}
In javscript console shows passing data
0 : {Id: "1", Name: "abc", Country: "uk", __rowNum__: 1}
1: {Id: "2", Name: "kala", Country: "us", __rowNum__: 2}
2: {Id: "3", Name: "Has", Country: "IN", __rowNum__: 3}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要进行反思。
sample .net小提琴
You need to work with the Reflection.
Sample .NET Fiddle