BsonDocument转List并作为数据源绑定到GridView
环境
IDE: vs 2019
框架:.NET Framework 4.5.2
(因为要使用的库对版本有要求,所以这里要注意.NET的版本)
项目类型:ASP.NET Web应用程序( .Net Framework)
使用到的库:
MongoDB.Bson v2.10.4
MongoDB.Driver v2.10.4
(推荐使用NuGet安装,Nuget使用请百度)
准备工作
确保你已经连接到MongoDB,获取到了类型为BsonDocument的集合。
下面是参考代码:
MongoClient client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("knowledgeManage");
var collection = db.GetCollection<BsonDocument>(Request.QueryString["name"]);
//应该了解:Collection是document的集合,document是BsonElement的集合
//BsonElement是name/value的键值对
BsonDocument Bsons = collection.Find(new BsonDocument()).FirstOrDefault();
BsonDocument detailDoc = new BsonDocument();
foreach (BsonElement bson in bsons)
{
if (bson.Name == "_id")//不在GridView中显示自动生成的 “_id”
continue;
detailDoc.Add(bson);
}
转换
其实就一行,但是,网上能百度到的都过于麻烦,其实只需要一行就够了(可能是用的库不一样的原因)
List<BsonElement> datasource = detailDoc.Elements.ToList();
将得到的List作为数据源绑定到GridView
后端代码:
GridView1.DataSource = datasource;
GridView1.DataBind();
如果你在这之前只是把GridView从工具箱里拖出来,那你可能会遇到这样的问题:
解决方法:
在设计页面,GridView任务中选择“编辑列”
添加BoundField,在右侧的属性中设置datafield
本例中设置为Name(想要绑定的字段名),HeaderText设置为Name(列名)。
剩下的依次添加即可。
注意事项:去掉左下角自动生成字段的勾选框,否则结果会变成: