[RESOLVED]MVC 5 – Populating List<T> in Model with other fields….

Hi All, 

  I’m really kind of new to Linq and MVC.  I’m stuck on this issue…  I have a class with the following fields:

public class CustomerContracts
public int CustomerId { get; set; }
public string Name { get; set; }
public string Email{ get; set; }
public List<Contract> Contracts { get; set; }   // I need to populate this with the correct contracts

Customer ID, Name and Email are part of one table (Customer Model Class) and the Contract is a few fields from the (Contract Model Class – see below).

public class Contract
public int Id { get; set; }
public string ContactName { get; set; }
public DateTime ContractDate { get; set; }
public int CustomerId { get; set; }

I created the above class CustomerContracts to bring the two tables together.  What I’m trying to do basically is populate the list of contracts on the basis of customer id.  I have some customers with 1 contract and some with 20.  I want to fill
that model up accordingly so I can do a list view of all the customers and there contract under them.  Here’s the break down… 

John Doe
1/1/2014   CTS01 
1/19/2014 DLLPS
4/20/2014 CTS14

David Hoper
1/16/2014  PROA44

I greatly appreciate your help… 

Ok I was able to get the model populated correctly now I need some help on determining if there is a better way to do this….

        public ActionResult Index()
            var customers = _db.Customers.ToList();
            var contracts = _db.Contracts.ToList();

            var model = new List<CustomerContracts>();

            foreach(Customer currentCustomer in customers)
                var currentCustomerContract = new CustomerContracts();

                currentCustomerContract.CustomerId = currentCustomer.Id;
                currentCustomerContract.Name = currentCustomer.Name;
                currentCustomerContract.Email = currentCustomer.Email;

                currentCustomerContract.Contracts = contracts.Where(c => c.CustomerId == currentCustomer.Id).ToList();


            return View(model);

Hi rperreta,

Thanks for your post.

Your way is good.

#Model Binding to List of Objects in ASP.NET MVC


Best Regards,


Leave a Reply