Object contains no Id definition
Mistake:
{"'object' does not contain a definition for 'Id'." }
ViewModel
public class PilotoVM
{
private FormulaEntities1 db = new FormulaEntities1();
public IQueryable<object> calcularValoracion()
{
return db.Piloto.GroupBy(p => p.id).Select(p => new { Id = p.Key, Valoracion = p.Sum( i=> i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia)});
}
}
controller
public ActionResult Index()
{
ViewBag.valoracion = pilotoVM.calcularValoracion();
return View(piloto.ToPagedList(pageNumber, pageSize));
}
View
@foreach (var pil in ViewBag.valoracion)
{
<p>@pil.Id</p>
<p>@pil.Valoracion</p>
}
Mistake in pil.Id
source to share
Your method calcularValoracion()
returns an anonymous object. Anonymous types are internal and cannot be accessed in the view (see this article for a good explanation).
Instead, create a view model to represent the data
public class PilotoVM
{
public int Id { get; set; }
public int Valoracion { get; set; }
}
then in the controller
List<PilotoVM> model = db.Piloto.GroupBy(p => p.id).Select(p => new PilotoVM()
{
Id = p.Key,
Valoracion = p.Sum( i=> i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia)
}).ToList();
Now you can revert the strongly typed model to your view and access the properties of each object PilotoVM
in the loop.
source to share
You must either create a strongly typed object representing your Id and Valoracian, or use a Tuple.
public List<Tuple<int, int>> calcularValoracion()
{
return db.Piloto
.GroupBy(p => p.id)
.Select(p => new Tuple<int, int>(
p.Key,
p.Sum(i => i.agresividad + i.paciencia + i.reflejos + i.valentia + i.valentia))
.ToList();
}
View
@foreach (var pil in ViewBag.valoracion)
{
@pil.Item1
@pil.Item2
}
Pay attention to .ToList()
at the end of the request. This will resolve your request to the memory collection so that you don't leak into the context of your view.
Finally, method names in C # should be Pascal Cased for example CalcularValoracion()
.
source to share