Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use rowspan in MVC-Razor, without javascript?

How can I merge cells in a table using rowspan inside a Razor view?

  • Without using javascript/jQuery.
  • The table's source is an IEnumerable.
  • Some of the items in the source will have the same value in a certain field and those are the one we want to merge in one cell.
  • We don't know how many times a given value is repeated.

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:

Categories

  • Electronics
  • Groceries

Products

  • Laptop (Electronics)
  • iPod (Electronics)
  • TV (Electronics)
  • Coffee (Groceries)
  • Cookies (Groceries)

The result

╔═════════════╦════════╗
║ 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!

like image 735
Marques Avatar asked May 10 '26 16:05

Marques


1 Answers

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; }
}
like image 107
Artiom Avatar answered May 13 '26 13:05

Artiom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!