views:

57

answers:

2

I'm pulling data from MongoDB in C# Asp.net MVC2. Here is the code I'm using in the controller.

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();

Now I'm unsure how to read the data out in the view. The documents dictionary should have some value pairs like:

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

When I add it in the view like so:

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

I get the output:

MongoDB.Driver.Cursor+<>c__Iterator0

Can someone point me in the right direction?

+1  A: 

ViewData is a container of objects. You need to cast it back to its native type before you can use it. Something like this (assuming that your dictionary is a Dictionary<string,string>:

<p>
    Name: <%: ((Dictionary<string, string>)ViewData["Document"])["Name"] %>
    ...
</p>
Gabe Moothart
When I use the code above I get this error: "InvalidCastException was unhandled by user code. Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.Int32,System.String]' to type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'. I have also just created a generic dictionary and tried to pass it to the view. That gave me the same error. Is there something I else that needs to be done in the view before I can using this statement?
rross
+1  A: 

To start off don't use ViewData. Always use strongly typed views.

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());

Then strongly type the view and iterate over the model:

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

If you are lucky you might even get IntelliSense in the view that will offer you properties of the model.

Darin Dimitrov
When I try to use documents.ToArray() I get this error: Systems.Collections.Generic.IEnumerable<MongoDB.Driver.Document> does not contain a definition for 'ToArray' etc....
rross