2010-07-22 104 views
2

我从C#Asp.net MVC2中的MongoDB中提取数据。这是我在控制器中使用的代码。将字典传递给视图Asp.net MVC

var mongo = new Mongo(); 
mongo.Connect(); 

var db = mongo.GetDatabase("DDL"); 
var Provinces = db.GetCollection("Provinces"); 
var documents = Provinces.FindAll().Documents; 
ViewData["Document"] = documents; 

return View(); 

现在我不确定如何在视图中读取数据。该文件字典应该有这样一些值对:

Name: someName, 
Lat: 39.1, 
Lon: 77, 
note: test not 

当我在视图中添加它像这样:

<p><%: ViewData["Document"]%></p> 

我得到的输出:

MongoDB.Driver.Cursor+<>c__Iterator0 

有人能指出我在正确的方向?

回答

1

ViewData是对象的容器。在使用它之前,您需要将其重新转换为其本机类型。像这样的东西(假设你的词典是一个Dictionary<string,string>:。

<p> 
    Name: <%: ((Dictionary<string, string>)ViewData["Document"])["Name"] %> 
    ... 
</p> 
+0

当我使用上面的代码时,出现此错误:“InvalidCastException未被用户代码处理。无法强制类型为'System.Collections.Generic.Dictionary'2 [System.Int32,System.String]'的对象类型为'System.Collections.Generic.Dictionary'2 [System.String,System.String]'。我也刚刚创建了一个通用字典,并试图将其传递给视图。这给了我同样的错误。在我能使用这个陈述之前,在视图中是否还有其他需要完成的事情? – rross 2010-07-25 14:43:35

2

要开始不使用ViewData始终使用强类型的意见

var mongo = new Mongo(); 
mongo.Connect(); 
var db = mongo.GetDatabase("DDL"); 
var Provinces = db.GetCollection("Provinces"); 
var documents = Provinces.FindAll().Documents; 
return View(documents.ToArray()); 

然后强类型的视图和迭代型号:

<% foreach (var item in Model) { %> 
    <div><%: item %></div> 
<% } %> 

如果你是幸运的,你甚至可以在将为您提供模型的性能视图得到智能

+0

当我尝试使用documents.ToArray()时出现此错误:Systems.Collections.Generic.IEnumerable 不包含'ToArray'等的定义.... – rross 2010-07-25 14:57:33

相关问题