[Asp .Net MVC]使用Razor處理View中的Table Rowspan (並處理 table-striped)

有時後我們會有資料需在表格中跨行的需求

例如John成績有三個科目 我們希望John跨行置中

其餘歷史、數學、科學再依序一行一列

 

同時因為Bootstrap內建的table-striped在此情況下會失效

(因為已經不是1 3 5、2 4 6 行不同底色這麼簡單了)

所以同時我們會自訂一個toggle的function來處理這個問題

 

完整程式碼如下

@model IEnumerable<Repository.Models.Grade>
@{
    ViewBag.Title = "Hello World!";
}
<h2>@ViewBag.Title</h2>
<style>
    .table > tbody > tr > th {
        text-align: center;
        background-color: #333;
        color: white;
    }

    .table > tbody > tr > td {
        vertical-align: middle;
        text-align: center;
    }

    .striped-1 {
        background-color: #f9f9f9;
    }

    .striped-2 {
        background-color: white;
    }
</style>
<p>
    <br />
    <table class="table table-condensed table-bordered">
        <tr>
            <th>Name</th>
            <th>Subject</th>
            <th>Score</th>
        </tr>
        @{string bgClass = "striped-1"; }
        @foreach (var student in Model.GroupBy(q => new { q.Name}).Distinct().OrderBy(q => q.Key.Name).ToList())
        {
            var row = Model.Where(q => q.Name == student.Key.Name).OrderBy(q => q.Subject).ToList();
            int count = row.Count();
            @:<tr class="@bgClass">
                <td rowspan="@count">@student.Key.Name</td>
        int rowCounter = 0;
        foreach (var data in row)
        {
            rowCounter++;

                <td>@data.Subject</td>
                <td>@data.Score</td>
                if (rowCounter == count)
                {
                    bgClass = toggleClass(bgClass);
                    @:</tr>
                }
                else
                {
                    @:</tr>
                    @:<tr class="@bgClass">
                }
            }
        }
</table>
</p>
@functions{
    private static string toggleClass(string className)
    {
        return (className == "striped-1") ? "striped-2" : "striped-1";
    }
}