I'm trying to get specific data from different tables based on some requirements, The program is supposed to take some columns of choosing from tables: Contatti, Contacts and Companies which are at different locations and bring them together.
Contact is connected to Companies through CompanyID
What i want is to display the company name basing on the CompanyID field in Contact table. The problem is that i iterate through a list to get the data in the view, and because of that i can't seem to get a company name based on the company ID attribute which is the Contact Foreign Key to the Companies table, what i get is all the companies names, because they're in the same list.
I'm sure there is an easy way to do this but this is a new world for me, thank you for any help.
Contact Model:
public class Contact
{
[Key]
public int ContactId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[ForeignKey("Companies")]
public int CompanyId { get; set; }
public virtual ICollection<Companies> Companies { get; set; }
[Required]
//public virtual Contatti Contatti { get; set; }
public virtual ICollection<Contatti> Contatti { get; set; }
}
Companies model:
public class Companies
{
[Key]
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public string CompanyAddress { get; set; }
public string CompanyCity { get; set; }
public string CompanyState { get; set; }
public string CompanyZip { get; set; }
public string CompanyArea { get; set; }
}
Controller:
public ActionResult Index(String Page)
{
ContactsUni2 CU = new ContactsUni2();
CU.Contattis = db2.Contatti.ToList();
CU.Contacts = db.Contacts.ToList();
CU.Companies = db.Companies.ToList();
List<ContactsUni2> contactlist = new List<ContactsUni2>();
contactlist.Add(CU);
return View(contactlist);
}
View:
@foreach (var item in Model)
{
for (int i = 0; i < item.Contacts.Count; i++)
{
<tr>
<td>
@item.Contacts[i].ContactId
</td>
<td>
@item.Contacts[i].Name
</td>
<td>
@item.Contacts[i].Address
</td>
<td>
@item.Contacts[i].CompanyId
</td>
@if (@item.Contacts[i].CompanyId == item.Companies[i].CompanyId)
{
<td>
@item.Companies[i].CompanyName
</td>
<td>
@item.Companies[i].CompanyCity
</td>
<td>
@item.Companies[i].CompanyArea
</td>
}
}
</tr>
<tr>
<td>
@item.Contattis[i].ContattoID
</td>
<td>
@item.Contattis[i].Nome
</td>
<td>
@item.Contattis[i].Citta
</td>
<td>
@item.Contattis[i].CodicePostale
</td>
<td>
@item.Contattis[i].Email
</td>
</tr>
}
}
</table>
</body>
</html>