I'm working on an ASP.Net MVC project, and I've hit a (seemingly) very strange error. I have a model named Lens, here is the class structure for it
public class Lens
{
public int LensID { get; set; }
public string LensName { get; set; }
}
In one of my views, I have a list of lenses (acquired in controller). I'm getting an ArgumentOutOfRangeException in the following code snippet
@for (int i = 0; i < Lenses.Count; i++)
{
<input type="text" data-LID="@Lenses[i].LensID" value="@Lenses[0].LensName" readonly id="lens @i" />
}
Lenses is the list I get from the controller. I really can't understand why this code is throwing an exception. I looked at the Locals view in my debugger and found that, at the time that the exception is thrown, the value of the argument i is 0, and there is a Lens object at index 0 of Lenses. Even stranger, when I use a foreach loop to pull from the exact same list, it has no issue retrieving the object. I've also tried
@Lenses[0].LensID
Instead, and I got the same error. Also, in case it's relevant. According to the Locals view, the Lenses list has a Count of 1. Here's the creation of Lenses
List<Lens> Lenses = (List<Lens>)ViewBag.Lenses;
And here's how it's being sent to the View from Controller
LensQueries lQuery = new LensQueries();
ViewBag.Lenses = lQuery.GetAll();
And here's the reference for LensQueries.GetAll()
public List<Lens> GetAll()
{
List<Lens> retList;
using (var context = new SqlDbContext())
{
retList = context.Lenses.SqlQuery("select *from dbo.Lens").ToList<Lens>();
}
return retList;
}