Reputation: 79
I have tried muplitple approaches here, but I am still not understanding how I can access the data from my join-table in MVC.
Here are my models:
public class Company
{
public int ID { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<Firm> Firm { get; set; }
}
public class Firm
{
public int ID { get; set; }
public string FirmName { get; set; }
public virtual ICollection<Company> Company { get; set; }
}
This creates the join-table "FirmCompany" in my database with "Firm_ID" and "Company_ID".
I have added one record to this table with data "645" and "330" respectively.
In my controller I have the following code to get the data:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company company = db.Company.FirstOrDefault(u => u.ID == id);
var companies = company.Firm;
if (company == null)
{
return HttpNotFound();
}
return View(companies);
}
When I enter the details view for the correct company I get the following error:
If I try this approach in my controller:
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company company = db.Company.FirstOrDefault(u => u.ID == id);
if (company == null)
{
return HttpNotFound();
}
return View(company);
I just get this text in my view: System.Collections.Generic.HashSet`1[KPForms.Models.Company]
Any tips as to where I am going wrong?
Edit: I have tried numerous flavours in the view as well. Current code in view:
<div>
<h4>Company</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.CompanyName)
</dt>
<dd>
@Html.DisplayFor(model => model.CompanyName)
</dd>
<dd>
@Html.DisplayFor(model => model.Firm)
</dd>
</dl>
</div>
Also tried a foreach in the view:
<div>
<h4>Company</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.CompanyName)
</dt>
<dd>
@Html.DisplayFor(model => model.CompanyName)
</dd>
<dd>
@foreach (var item in Model) {
@Html.Displayfor(item => item.Firm)
</dd>
</dl>
</div>
Upvotes: 0
Views: 81
Reputation: 2543
First of all, it would be nice to see what your View code looks like.
Not having that, I thought I would provide you with a working solution:
Controller:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company company = db.Company.FirstOrDefault(u => u.ID == id);
if (company == null)
{
return HttpNotFound();
}
return View(company);
}
View:
@model KPForms.Models.Company
<p>Company: @Model.CompanyName</p>
<p>Firms:</p>
<ul>
@foreach(var firm in Model.Firm){
<li>@firm.FirstName</li>
}
</ul>
Upvotes: 1