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"]
Related
I am passing a List with two different types to my view from the controller Example1 and Example2. I am foreaching through the List to display its contents. I can see the two list in the Object List, [0]-5 Entries and [1]-4 Entries. 1st entry is my Example1Deatil and Second is my Example2Detail.
What i am trying to do is have Example1 to be built out on one table and Example2 on another by checking the type. I know they are of Type Object so trying to figure out how to get their original type. so the type checks work correctly.
Edit: What i am passing in is two List one of type Example1Deatil and Example2Detail. They are both in the List(object) that was passed in.
#foreach (var item in Model)
{
//Edit: This is how I got my List<Object> that contained my two
// List of List<Example1> and List<Example2> to work.
foreach(var result in item as IEnumerable<object>
// This was the problem ^^^^^^^^^^^^^^^^^^^^^
// The list in the list where just type object and not a List of Objects.
// and now everything is working. Thank you to those who helped.
if (result is Models.Example1Models.Example1Detail)
{
<table>
//Example1 contents are different than Example2's contents.
</table>
}
if (result is Models.Example2Models.Example1Detail)
{
<table>
//Example2 Contents
</table>
}
Controller
public ActionResult Contact()
{
IList<object> list = new List<object>();
list.Add(1);
list.Add("one");
return View(list);
}
View
#model System.Collections.Generic.IEnumerable<object>
#foreach (var result in Model)
{
if (result is int)
{
<div>int</div>
}
if (result is string)
{
<div>string</div>
}
}
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>
I have this code:
public ActionResult DeleteBehandling(int id)
{
AppointmentDiary _ad = new AppointmentDiary();
var beh = _db.Behandlingar.Single(k => k.BehandlingarId == id);
foreach (var item in _ad.BehandlingarId)
{
if (_ad.BehandlingarId == id)
{
return View();
}
}
_db.Behandlingar.Remove(beh);
_db.SaveChanges();
return RedirectToAction("BehandlingarNy");
}
_ad.BehandlingarId is a column in my database containing int. Now, I want to loop through this column to see if I get a match with the input. I get this error:
foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator.
How do I get past this?
Thanks!
_ad.BehandlingarId is an int column as you say.
So you should not iterate over it.
Instead you should use something like this
foreach (var item in _ad)
{
if (item.BehandlingarId == id)
{
return View();
}
}
You're trying to loop over something that's not a collection (BehandlingarId is an int) - at a guess, i'd suggest you need to change your loop to this:
foreach (var item in _ad)
{
....
This code obtains a listing of unique org names for display within my .cshtml page:
IEnumerable<dynamic> data = db.Query("Select * from provider
where submitter_element = '210300'");
//the 210300 could be any value passed to the query
var items = data.Select(i => new { i.org_name }).Distinct();
foreach(var name in items){
<text>#name.org_name<br></text>
The records in data are each unique themselves, but the data in each field contains the same values i.e. multiple providers have the same org_name.
I want to be able to reuse the data multiple times to create multiple unique lists. I was hoping to pass this to a #helper for display. To that end, I have the following:
#helper ListBoxDistinctDisplay(IEnumerable<dynamic> queryResult)
{
IEnumerable<dynamic> distinctItems = queryResult.Select(i => new { i.org_name }).Distinct();
foreach(var listItem in distinctItems){
<text>#listItem.org_name<br></text>
}
Then in my .cshtml page I do this:
#DisplayHelpers.ListBoxDistinctDisplay(data)
...and BINGO, I get my unique list on my "view" page.
The works perfectly, except as you see I am having to indicate .org_name within the helper.
My question is how can I pass the field name (org_name) into the helper so that my helper can be re-used no matter he field name?
OR...is there a totally different approach all together that I am unaware of?
THANKS!
Since you like to use dynamic, I'll stick with that.
You may want to pass selector:
#helper ListBoxDistinctDisplay(IEnumerable<dynamic> queryResult, Func<dynamic, dynamic> selector)
{
IEnumerable<dynamic> distinctItems = queryResult.Select(x => new {selectedField = selector(x)}).Distinct();
foreach (var listItem in distinctItems)
{
<text>#listItem.selectedField<br/></text>
}
}
Call it:
#DisplayHelpers.ListBoxDistinctDisplay(data, x => x.org_name)
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>