Access element of ilist MVC

726 Views Asked by At

ViewModel:

public class ViewModel
{
    public IList<Car> Cars { get; set; }
}

Model:

public class Car
{
    int id { get; set };
    string Color { get; set };
}

Post Action:

public ActionResult Select(ViewModel model)
{
    foreach(var car in model.Cars) 
    {
        carId = car.Id;
        // more code...
    }
    return RedirectToAction("one","two",new { carId });
}

How to access for this element? Is this right?

1

There are 1 best solutions below

8
Claudio Redi On

Cars is a list of Car objects, it doesn't have an Id property. You need to access items on the list in order to get car's ids

It's hard to know what you specifically want to do. Do you have a single element on the list? Then something like this would do the trick

int carId = model.Cars.First().Id;

Do you need to iterate over elements in the list. Then you need to use a foreach loop

int carId = 0;
foreach(var car in model.Cars) 
{
    carId = car.Id;
    // more code...
}

If you need to select ALL ids then something like this would do the trick

var carsIds = model.Cars.Select(c => c.Id);