How to read the content of List in a View in ASP.NET MVC3

71 Views Asked by At

So I have this code:

public ActionResult Agregar(int id)
        {
            Producto producto = db.Productos.Find(id);

            var list = new List<Carrito> { 
                new Carrito { ProductId = producto.ID, Cantidad = 1, PrecioUnitario = producto.Precio } 
            };

            return View(list);
        }

and I pass the variable list to the View, the problem is, I don't know how to access ProductId or Cantidad

Any idea how to do this?

Also, let's suppose the variable list has multiple objects, how to print the result of every object through a foreach

1

There are 1 best solutions below

2
On BEST ANSWER

Your view (Agregar.cshtml) should be like this.

@model IEnumerable<Carrito>

<h2>We are gonna show the items in a loop now..</h2>
@foreach(var item in Model)
{
  <p>@item.ProductId</p>
  <p>@item.Cantidad </p>
}