記事詳細


投稿日
2026年10月27日21時48分
タイトル

ASP.NET Core MVC: bootstrapのテーブルの行の背景色を指定する方法を教えてください。

内容

ASP.NET Core MVCでBootstrapのテーブル行の背景色を指定する方法は、基本的には Bootstrapのユーティリティクラス または CSSのカスタマイズ を使います。
ASP.NET Core MVCでは、Views 内の .cshtml ファイルにHTMLとBootstrapクラスを記述すればOKです。

1. Bootstrapの組み込み背景色クラスを使う方法

Bootstrapには行やセルに適用できる背景色クラスがあります。

クラス名色
table-primary青系
table-secondaryグレー系
table-success緑系
table-danger赤系
table-warning黄系
table-info水色系
table-light明るい灰色
table-dark黒系

例: .cshtml ファイル

Cshtml
@{ ViewData["Title"] = "Bootstrap Table Example"; } <div class="container mt-4"> <h2>背景色付きテーブル行</h2> <table class="table table-bordered"> <thead> <tr class="table-primary"> <th>ID</th> <th>Name</th> <th>Status</th> </tr> </thead> <tbody> <tr class="table-success"> <td>1</td> <td>Tanaka</td> <td>Active</td> </tr> <tr class="table-danger"> <td>2</td> <td>Suzuki</td> <td>Inactive</td> </tr> <tr class="table-warning"> <td>3</td> <td>Yamada</td> <td>Pending</td> </tr> </tbody> </table> </div>

✅ ポイント

  • 行 (<tr>) に直接クラスを付けることで背景色が変わります。
  • セル (<td>) に付けても同じ効果があります。

2. 独自CSSで背景色を指定する方法

Bootstrapの色では足りない場合は、自分でCSSを追加します。

_Layout.cshtml または個別ビューにCSS追加

Html
<style> .custom-row { background-color: #ffe4b5; /* モカ色 */ } </style>

.cshtml 内で適用

Cshtml
<tr class="custom-row"> <td>4</td> <td>Kato</td> <td>Custom Color</td> </tr>

3. 条件付きで背景色を変える(Razor)

ASP.NET Core MVCでは、モデルの値に応じてクラスを切り替えることもできます。

Cshtml
@foreach (var item in Model) { var rowClass = item.Status == "Active" ? "table-success" : item.Status == "Inactive" ? "table-danger" : "table-warning"; <tr class="@rowClass"> <td>@item.Id</td> <td>@item.Name</td> <td>@item.Status</td> </tr> }

✅ ポイント

  • Razorの条件分岐でクラスを動的に設定できます。
  • データに応じて色分けする場合に便利です。

💡 まとめ

  • 簡単に色を付けたい → Bootstrapの table-* クラスを使う
  • 独自色を使いたい → CSSを追加してクラスを適用
  • データに応じて色を変えたい → Razorで条件分岐してクラスを設定

もし希望があれば、次は ASP.NET Core MVCでデータベースから取得した値に応じて行の背景色を変える完全サンプル を作成できますが、それを作りますか?
これなら実運用でもすぐ使えます。

Powered by Froala Editor

添付画像

画像はありません
Genreのカテゴリ-名
Views
編集 | 記事一覧