I have a foreach looping through a List of objects in an ASP.NET MVC/Razor project. I’m trying to use to index of the current object to determine if there is another object in the list.
Every time through the loop, I’m getting -1 as the value returned from Model.TodaySoups.IndexOf(soup) in the following code:
@foreach(MenuItem soup in Model.TodaysSoups)
{
int i = Model.TodaysSoups.IndexOf(soup);
string comma = i < Model.TodaysSoups.Count ? "," : "";
<li class="soup">@soup.Name@comma </li>
}
TodaysSoups is defined as:
public List<MenuItem> TodaysSoups
I’ve also tried defining soup implicitly:
var soup in Model.TodaysSoups
didn’t help.
As far as I know, this should work. Clearly, I mistaken. Any help would be appreciated.
Update:
Any off by one issues you can ignore, I’ve been staring at this for a while and just trying whatever I could think of, but, thank you for trying to help me with them. The weird part is that I’m getting -1 every time.
The MenuItem definition
public class MenuItem
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public List<MenuOption> Options { get; set; }
public bool IsAvailable { get; set; }
public bool IsSpecial { get; set; }
public MenuItem()
{
this.IsAvailable = true;
this.IsSpecial = false;
this.Options = new List<MenuOption>();
}
}
Worth noting:
I had originally planned on using EF, but we’re using the Enterprise Library 5.0 DAAB at work, so I switched over so I could get used to using that. I then ripped out what I believed to be all references to EF in my code and config files, and there’s a very real possibility that I missed something, because I’m really not familiar with it. Possible cause?
Quick fix: use a for-loop.