MVC 3 Razor Displaying parent/child tables as one table
asp.net-mvc-3, entity-framework, razor
Solution
Maybe there are more elegant solutions exist, but here is how I would do it.
You need one loop to generate the header rows from `Foo.Number` then you need a second loop where you select all the `Bar`s and group them by their `Name`. From these groups you can generate the data rows.
Now you only need a thrid loop which goes through the `Bar.Value`s and builds the table row.
So the above described "algorithm" in code:
<table>
<tr>
<td>
</td>
@foreach (var f in Model.OrderBy(f => f.FooID))
{
<td>@f.Number
</td>
}
</tr>
@foreach (var group in Model.SelectMany(f => f.Bars).GroupBy(b => b.Name))
{
<tr>
<td>@group.Key
</td>
@foreach (var b in group.OrderBy(b => b.FooID))
{
<td>@b.Value
</td>
}
</tr>
}
</table>
Note: I've added the `OrderBy(b => b.FooID)` to make sure that the `Bar` values correctly aligned with the `Foo.Number` headers.
And this how the result looks like:
Problem
I have two 2 tables in my database ``` Table: Foo Table: Bar ----------------- --------------------- |FooID | Int| |BarID | Int | |Number | Int| |FooID | Int | ----------------- |Name | String | |Value | Int | --------------------- With data with data |FooID | Number | |BarID |FoodID |Name |Value | |1 | 1 | |1 |1 |apple |100 | |2 | 2 | |2 |1 |orange |110 | |3 |2 |apple |200 | |4 |2 |orange |40 | ``` These are the related models ``` class Foo { public int FooID { get; set; } public int Number { get; set;} public virtual ICollection<Bar> Bars { get; set; } } class Bar { public int BarID { get; set; } public int FooID { get; set; } public string Name { get; set;} public int Value { get; set;} } ``` I can easly display this in a table like format by doing the follwing in the view ``` <table> @foreach(var f in Model) { <tr> foreach(var b in f.Bar) { <td>@f.Number</td> <td>@b.Name</td> <td>@b.Value</td> } </tr> } </table> ``` Which outputs ``` ------------------- |1 |apple |100| ------------------- |1 |orange |110| ------------------- |2 |apple |200| ------------------- |2 |orange | 40| ------------------- ``` What I'd really to see for the output is the following. ``` ------------------------- | | 1 | 2 | ------------------------- |apple |100 |200 | ------------------------- |orange |200 | 40 | ------------------------- ``` Can someone please point me in the right direction???