記事詳細


投稿日
2026年01月05日21時41分
タイトル

.NET 8 の ASP.NET Core MVC で、データベースから取得したカテゴリーごとの複数の Reference ページリンクを左サイドバーに表示する方法

内容

検索キーワード

asp.net mvc .net8 「データベースから、カテゴリー分けされた複数のreferenceページへのメニュー」を左Sidebarに作成する方法を教えてください。 modelは、category.csとreferencepage.csです。referencepageクラス内には、”string content"フィールドを含めてください、



モデル定義(CategoryReferencePage

Csharp
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace YourApp.Models { public class Category { public int Id { get; set; } [Required, StringLength(100)] public string Name { get; set; } // ナビゲーションプロパティ public List<ReferencePage> ReferencePages { get; set; } = new(); } public class ReferencePage { public int Id { get; set; } [Required, StringLength(200)] public string Title { get; set; } public string Content { get; set; } // 本文 // 外部キー public int CategoryId { get; set; } public Category Category { get; set; } } }

2. DbContext 設定

Csharp
using Microsoft.EntityFrameworkCore; using YourApp.Models; namespace YourApp.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Category> Categories { get; set; } public DbSet<ReferencePage> ReferencePages { get; set; } } }

Program.cs に DbContext 登録:

Csharp
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

appsettings.json に接続文字列を設定:

Json
"ConnectionStrings": { "DefaultConnection": "Server=localhost;Database=YourDb;Trusted_Connection=True;TrustServerCertificate=True;" }

3. サイドバー用 ViewComponent 作成

ViewComponent を使うと、どのビューからでも簡単に呼び出せます。

Components/SidebarMenu/SidebarMenuViewComponent.cs

Csharp
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using YourApp.Data; namespace YourApp.Components { public class SidebarMenuViewComponent : ViewComponent { private readonly AppDbContext _context; public SidebarMenuViewComponent(AppDbContext context) { _context = context; } public async Task<IViewComponentResult> InvokeAsync() { // カテゴリーとその中の ReferencePages を取得 var categories = await _context.Categories .Include(c => c.ReferencePages) .OrderBy(c => c.Name) .ToListAsync(); return View(categories); } } }

4. ViewComponent のビュー作成

Views/Shared/Components/SidebarMenu/Default.cshtml

Razor
@model IEnumerable<YourApp.Models.Category> <div class="sidebar"> <ul class="list-group"> @foreach (var category in Model) { <li class="list-group-item"> <strong>@category.Name</strong> <ul class="list-unstyled ms-3"> @foreach (var page in category.ReferencePages) { <li> <a asp-controller="ReferencePages" asp-action="Details" asp-route-id="@page.Id"> @page.Title </a> </li> } </ul> </li> } </ul> </div>

5. レイアウトに組み込み

Views/Shared/_Layout.cshtml のサイドバー部分に追加:

Razor
<div class="row"> <div class="col-3"> @await Component.InvokeAsync("SidebarMenu") </div> <div class="col-9"> @RenderBody() </div> </div>

6. ReferencePagesController(詳細ページ表示用)

Csharp
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using YourApp.Data; namespace YourApp.Controllers { public class ReferencePagesController : Controller { private readonly AppDbContext _context; public ReferencePagesController(AppDbContext context) { _context = context; } public async Task<IActionResult> Details(int id) { var page = await _context.ReferencePages .Include(r => r.Category) .FirstOrDefaultAsync(r => r.Id == id); if (page == null) return NotFound(); return View(page); } } }

7. 詳細ページビュー

Views/ReferencePages/Details.cshtml

Razor
@model YourApp.Models.ReferencePage <h2>@Model.Title</h2> <div> @Html.Raw(Model.Content) <!-- HTMLを含む場合 --> </div> <p><a asp-action="Index" asp-controller="Home">戻る</a></p>

8. ポイント

  • ViewComponent を使うことで、サイドバーをどのページにも簡単に再利用可能。
  • Include で関連データ(ReferencePages)を一括取得。
  • Content フィールドは HTML を含む場合 @Html.Raw() で表示。
  • Bootstrap の list-group や ms-3 で簡単に階層メニューを作成。

✅ この構成で、DBのカテゴリー → その中の複数のReferenceページリンク が左サイドバーに表示され、クリックすると詳細ページが表示されます。

もし希望があれば、このサイドバーを アコーディオン形式(折りたたみ) にして、カテゴリーをクリックするとページ一覧が展開されるようにもできます。
次にそれを実装するコードも作れますが、作成しますか?


Powered by Froala Editor

添付画像

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