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?
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>
Related
I'm trying to create a simple Grid using GridMVC
Here is my Controller code.
public ActionResult Index()
{
var approvals = new List<Host_Apps>();
approvals = db.Host_Apps.ToList();
return View(approvals);
}
HTML:
#{
Layout = null;
}
#model List<TrackMiPD.Models.Host_Apps>
#using GridMvc.Html
<h2>Index</h2>
<body>
<div>
#Html.Grid(Model,"Index").Columns(columns =>
{
columns.Add(data => data.ApprovalId).Titled("First Name").SetWidth(110);
columns.Add(data => data.Name).Titled("Last Name").SetWidth(110);
columns.Add(data => data.State).Titled("Age").Sortable(true);
columns.Add(data => data.City).Titled("Birth Date").Sortable(true);
}).WithPaging(20)
</div>
</body>
I tried passing IEnumerable instead of List. I vaguely remember long agao I was working with GridMVC that after setting layout= Null it started working So ive put Layout as Null
Here is the error I get
The model item passed into the dictionary is of type
'GridMvc.Html.HtmlGrid1[TrackMiPD.Models.Host_Apps]', but this
dictionary requires a model item of type
'System.Collections.Generic.List1[TrackMiPD.Models.Host_Apps]'.
Try creating a wrapper class for List of Host_Apps, That would have a list of Host_Apps. Then pass it as model to your view.
During access in view access it as:
#Html.Grid(Model.Host_Apps)
The same problem I had but was able to walk away with this.
I am very new to asp.net and i am stuck on that code i cant resolve this error
"The model item passed into the dictionary is of type 'AMSPractice.Models.AddTable', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[AMSPractice.Models.AddTable]'."
I want to show only one value for example in my table there is more than one values name "first" so i want to show only one time "first" so when we write
FirstOrDefault then give error and when we write Where then error is not shown
but i want back only one value where return more then one values.
Here is my code
Controller
public ActionResult Login(string Name,string TeacherID)
{
AdmissionDBEntities obj = new AdmissionDBEntities();
AddTable t = new AddTable();
var v = obj.AddTables.FirstOrDefault(a => a.Teacher.Equals(Name) && a.Teacher_Id.Equals(TeacherID));
if (v != null)
{
**var var = obj.AddTables.FirstOrDefault(b => b.Teacher==Name);**
return View(var);
}
return RedirectToAction("/Home/Index");
and my View is:
#model IEnumerable<AMSPractice.Models.AddTable>
<h3>Classes Assigned</h3>
<br /><br />
<ul>
#foreach (var a in Model)
{
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = a.Foreign_Id }, null)
</li>
}
</ul>
Your issue is from the way you have strongly typed your view. From your controller, when you return return View(var); you are passing a single object to your view, yet your view is strongly typed to expect an IEnumerable of the AddTable object.
You either need to return an IEnumerable from your controller, or change your view to expect only a single object.
Try the following to change your view to expect only a single object.
In your view change your strongly typed #model from what you have to #model AMSPractice.Models.AddTable
At that point, you wouldn't need the foreach and you would just have the following.
<li>
#Html.ActionLink(a.Class,"Sections","Attendance", new { nid = Model.Foreign_Id}, null)
</li>
Hello I've had an issue with gathering an object from my Umbraco Blog page specificly cropping it down
#foreach (var item in Model.Content.Children.Where("visible==true"))
{
var BodyTextToCrop = item.GetProperty("bodytext").Value.ToString();
#item.Name<br />
#Umbraco.Truncate(BodyTextToCrop, 2, true)
}
Change your statement to the following:
#foreach (var item in Model.Content.Children.Where(x => x.IsVisible()))
{
var BodyTextToCrop = item.GetProperty("bodytext").Value.ToString();
#item.Name<br />
#Umbraco.Truncate(BodyTextToCrop, 2, true)
}
It looks like your where clause is using the dynamic access of the type and Model.Content could be strongly typed in your case.
Take a look at querying - MVC
Snippet on the page:
//dynamic access
#CurrentPage.Children.Where("Visible")
//strongly typed access
#Model.Content.Children.Where(x => x.IsVisible())
I'm using ASP.NET MVC- I've got a DropDownList rendered in a user control (ascx page). Here's the code from the ascx page:
<%: Html.DropDownList("climed_pharm_fk",
new SelectList(ViewData["Pharmacies"] as IEnumerable,
"pharm_pk", "pharm_name", Model.climed_pharm_fk))%>
<%= Html.ActionLink("Add New", "Create", "PharmacyMaintenance",
new { Area = "" },
new { target="_blank" })%>
Currently, "pharm_name" shows up in the drop down list. That's great and all, but I am needing "pharm_name" as well as "pharm_phone". I tried stuff like:
<%: Html.DropDownList("climed_pharm_fk",
new SelectList(ViewData["Pharmacies"] as IEnumerable,
"pharm_pk","pharm_name,pharm_phone",Model.climed_pharm_fk))%>
<%= Html.ActionLink("Add New", "Create", "PharmacyMaintenance",
new { Area = "" },
new { target="_blank" })%>
But that didn't work obviously. How does one go about doing this? Thanks in advance!
Try this:
<%: Html.DropDownList(
"climed_pharm_fk",
new SelectList
(
(ViewData["Pharmacies"] as IEnumerable)
.Select
(
a=> new
{
a.pharm_pk,
pharm_name = a.pharm_name + a.pharm_phone
}
),
"pharm_pk",
"pharm_name,pharm_phone",
Model.climed_pharm_fk)
)
%>
Passing the list of objects in viewdata is not a good practice. Views (or partial vies) should not contain logic as well. Also, you seem to be having a Model bound to partial (ascx) view as you are using Model.climed_pharm_fk.
Instead bind the partial view to a ViewModel, which will have the instance of whatever object the current Model is referencing and also, the list of "Pharmacies". Then you can have a property in view model returning the collection of pharmacy names. In the Get part of property you can move the code which collects all the 'pharm_name + pharm_phone' and return as collection of single string.
I'm trying to get a list of all area in my database:
public ActionResult Index()
{
var carreras = repo.FindAllCarreras().ToList();
AreaRepository area = new AreaRepository();
ViewData["Areas"] = area.FindAllAreas(); //Return IQueryable<>
return View("Index", carreras);
}
And in the View:
<% foreach (var area in ViewData["Areas"])
{ %>
<p><%: area %></p>
<% } %>
I get an error:
foreach statement cannot operate on variables of type 'object' because
'object' does not contain a public definition for 'GetEnumerator'
I think the best route would be modifying the query in the CarreraController and creating a linq query that returns all the names and saving it to a simple List<string>.
How can I achieve this?
ViewData["Areas"] = area.FindAllAreas().Select(????
ViewData is a dictionary from string to object. So you are basically doing
object o = ViewData["Areas"];
foreach(var area in o)
...
Just use a cast:
foreach(var area in (WhateverYourCollectionTypeIs)ViewData["Areas"])
cast ViewData["Areas"] to (IEnumerable<AREATYPE>)ViewData["Areas"]