Passing a dictionary to a view Asp.net MVC
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 pai开发者_如何学Crs 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?
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.
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>
精彩评论