[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
jdoe@aspnet.com
—————————————————–
Contracts
—————————————————–
1/1/2014   CTS01 
1/19/2014 DLLPS
4/20/2014 CTS14

David Hoper
dhoper@aspnet.com
-—————————————————-
Contracts
—————————————————–
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();

                model.Add(currentCustomerContract);
            }

            return View(model);
        }

Hi rperreta,

Thanks for your post.

Your way is good.

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

http://www.binaryintellect.net/articles/b1e0b153-47f4-4b29-8583-958aa22d9284.aspx

Best Regards,

Eileen

Leave a Reply