Reputation: 1914
How can I merge cells in a table using rowspan inside a Razor view?
The resulting HTML should be something like this:
<table>
<tr>
<td rowspan="2">Column 1 row 1</td>
<td>Column 2 row 1</td>
</tr>
<tr>
<td>Column 2 row 2</td>
</tr>
<tr>
<td rowspan="3">Column 1 row 3</td>
<td>Column 2 row 3</td>
</tr>
<tr>
<td>Column 2 row 4</td>
</tr>
<tr>
<td>Column 2 row 5</td>
</tr>
</table>
EDIT to add the data source and desired result:
The data source may be something like Products with Categories. Ex:
╔═════════════╦════════╗
║ Electronics ║ Laptop ║
║ ║ iPod ║
║ ║ TV ║
╠═════════════╬════════╣
║ Groceries ║ Coffee ║
║ ║ Cookies║
╚═════════════╩════════╝
The only way I have in mind is using Linq to count how many times a value is on the list, but I wanted to know if someone have a better solution. Thanks!
Upvotes: 3
Views: 6048
Reputation: 7837
Try something like this.
<table>
<tr>
<th>Movie</th>
<th>Person</th>
</tr>
@foreach (var byMovies in elements.GroupBy(x => x.Movie)
.OrderBy(movie => movie.Key.Name))
{
var secondRowOrHigher = false;
@:<tr>
@:<td rowspan="@byMovies.Count()">@byMovies.Key.Name</td>
foreach (var ticket in byMovies.OrderBy(x => x.Person.Name))
{
if (secondRowOrHigher)
{
@:<tr>
}
secondRowOrHigher = true;
<td>@ticket.Person.Name</td>
@:</tr>
}
}
</table>
and classes just to have a picture
public class TicketInfo
{
public Movie Movie { get; set; }
public Person Person { get; set; }
}
public class Person
{
public string Name { get; set; }
}
public class Movie
{
public string Name { get; set; }
}
Upvotes: 7