ナビゲーションメニューの作成
最終更新日:
このページはチュートリアルの一部であり、最初から最後まで順番に実行する必要があります。最初のページに移動します:Xperienceのインターフェース
このチュートリアルの前のステップでは、データベースからページデータを取得してライブサイトに表示する機能を実装しました。このステップでは、コンテンツ編集者がウェブサイトのナビゲーションを管理できるように、動的メニューをコーディングします。
ウェブサイトのナビゲーションは、サイトの現在のコンテンツや所有者の要件に基づいて変更される傾向があります。ページタイプのナビゲーション項目機能により、コンテンツ編集者は個々のページのメニューに表示するフラグを設定し、コンテンツツリーのどのページがナビゲーションメニューに表示されるかを制御することができます。
ライブサイトアプリケーションのコード側では、メニューの表示フラグに基づいてページデータを取得し、メニューの表示、デザイン、および動作を処理する必要があります。この動的なアプローチにより、サイトのコードを調整したり再展開したりする必要がなく、編集者はナビゲーションメニュー項目を完全に制御することができます。
以下について説明します
メニュー項目のビューモデルの作成
-
Visual Studioで、Modelフォルダ内にMenuフォルダを作成します。
-
Menuフォルダを選択し、新しくMenuItemViewModelクラスを作成します。
-
次のコードを使用して、ビューモデルのプロパティを定義します。
namespace MEDIOClinic.Models { public class MenuItemViewModel { // Defines the properties of the MenuItem view model public string MenuItemText { get; set; } public string MenuItemRelativeUrl { get; set; } } }
4.変更を保存します。
ナビゲーションメニューのビューコンポーネントの作成
ASP.NET Coreのビューコンポーネントを使ってサイトのナビゲーションメニューを追加します。ビューコンポーネントの InvokeAsyncメソッドは、サイトのナビゲーションメニューのコンテンツをロードして表示します。メソッドはメニューデータを取得し、コンポーネントのビューに渡される MenuItemViewModelsのコレクションに整理します。
-
Coreプロジェクトに新しいViewComponentsフォルダーを作成します。
-
新しいNavigationMenuViewComponentクラスをフォルダーに追加します。
-
クラスのデフォルトコードを次のように置き換えます。
using System.Threading.Tasks; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using CMS.Core; using CMS.DocumentEngine; using Kentico.Content.Web.Mvc; using MEDIOClinic.Models; namespace CoreTutorial.ViewComponents { public class NavigationMenuViewComponent : ViewComponent { private readonly IPageRetriever pageRetriever; private readonly IPageUrlRetriever urlRetriever; public NavigationMenuViewComponent() { // Initializes instances of required services // NOTE: This method of instantiating services is not recommended for // real-world projects and is only used for the sake of brevity in this tutorial. // Instead, we recommend configuring a dependency injection container to resolve // object dependencies (e.g., Autofac). See the Xperience documentation for details. pageRetriever = Service.Resolve<IPageRetriever>(); urlRetriever = Service.Resolve<IPageUrlRetriever>(); } public async Task<IViewComponentResult> InvokeAsync() { // Retrieves a collection of page objects with data for the menu (pages of all page types) IEnumerable<TreeNode> menuItems = await pageRetriever.RetrieveAsync<TreeNode>(query => query // Selects pages that have the 'Show in menu" flag enabled .MenuItems() // Only loads pages from the first level of the site's content tree .NestingLevel(1) // Filters the query to only retrieve required columns .Columns("DocumentName", "NodeID", "NodeSiteID") // Uses the menu item order from the content tree .OrderByAscending("NodeOrder")); // Creates a collection of view models based on the menu item data IEnumerable<MenuItemViewModel> model = menuItems.Select(item => new MenuItemViewModel() { // Gets the name of the page as the menu item caption text MenuItemText = item.DocumentName, // Retrieves the URL for the page (as a relative virtual path) MenuItemRelativeUrl = urlRetriever.Retrieve(item).RelativePath }); return View(model); } } }
-
変更を保存します。
このコードは、Xperience DocumentQuery API を使用して、すべてのページタイプのページデータを取得します。DocumentQuery は、SQL データベースの上に抽象化レイヤーを提供し、ページ データの取得方法を調整する追加のメソッドを呼び出すことができます。
たとえば、OrderByAscending メソッドでは、取得されるデータ項目の順序を設定し、Columns メソッドでは、基礎となる SQL クエリが必要なデータ列のみをロードするようにします。パフォーマンス上の理由から、すべてのデータ検索APIコールでカラムを制限することを強くお勧めします。
詳細はドキュメントを参照してください。API でのページの操作
ナビゲーションメニュービューの作成
ナビゲーションメニューは、ウェブサイトのほとんどのページに表示される要素です。ここでは、ビューコンポーネントによって返される部分ビューでメニューの出力を定義します。メニューは、サイトのメイン・レイアウトに追加することができます(必要に応じて他のページで再利用することもできます)。
-
Visual Studio の ~/Views/Shared の下に、新しい Components フォルダを作成します。
-
Componentsフォルダ内に、新しいNavigationMenuフォルダを作成します。
-
NavigationMenuフォルダ内に、Default.cshtmlという名前の新しいビューを作成します。
-
ビューのデフォルトコードを以下のように置き換えます。
@using MEDIOClinic.Models; @model IEnumerable<MenuItemViewModel> <nav> @foreach (MenuItemViewModel menuItem in Model) { @* Iterates through the view model collection and renders HTML links for the menu items *@ <a href="@menuItem.MenuItemRelativeUrl" title="@menuItem.MenuItemText">@menuItem.MenuItemText</a> } </nav>
-
変更を保存します。
ウェブサイトのレイアウトを更新する
ナビゲーションメニューの背後にある機能をコーディングしました。このコードを使って、サイトのレイアウトにメニューを追加してみましょう。
-
_Layout.cshtmlファイル(Views / Sharedフォルダー内)を編集します。
-
<nav>タグで定義されたセクションを見つけ、Component.InvokeAsync("NavigationMenu")呼び出しで置き換えます。これは、作成したDefault.cshtmlビューを使ってNavigationMenuViewComponentをレンダリングします。これは非同期操作なので、awaitディレクティブを含めることを忘れないでください!
-
MEDIOクリニックのロゴを表示する<header>セクションの<a>要素を探して、 href属性の値を~/homeに設定してください。
最終的な_Layout.cshtmlは以下のようになります。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
@* Dynamically resolves the page's title *@
<title>Medio Clinic - @ViewBag.Title</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato:400,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css">
<link href="~/css/styles.css" rel="stylesheet" type="text/css" />
@* Razor section for additional page-specific styles *@
@RenderSection("styles", required: false)
</head>
<body>
<header>
<div class="col-sm-offset-3 col-sm-6">
<div class="col-sm-6">
@* Targets the root page of the website *@
<a href="~/home" title="MedioClinic homepage" class="logo">MEDIO clinic</a>
</div>
<div class="col-sm-6 nav">
@* Renders the view component with the navigation menu, including the <nav> element *@
@await Component.InvokeAsync("NavigationMenu")
</div>
</div>
<div class="clearfix"></div>
</header>
@* Loads the content of your Tutorial's pages as sub views *@
@RenderBody()
<footer>
<div class="col-sm-offset-3 col-sm-6">
<div class="row">
<div class="col-sm-6">
<h4>MEDIO clinic</h4>
<ul>
<li><i class="fa fa-map-marker"></i> Address: <address>7A Kentico street, Bedford, NH 03110, USA</address></li>
<li><i class="fa fa-envelope-o"></i> E-mail: <a href="mailto:info@medio-clinic.com" title="Email us">info@medio-clinic.com</a></li>
<li><i class="fa fa-phone"></i> Phone number: <a href="tel:5417543010" title="Phone us">(541) 754-3010</a>
</ul>
</div>
<div class="col-sm-6">
<span class="cms">Powered by <a href="https://xperience.io/" title="Kentico Xperience CMS">Kentico Xperience CMS for ASP.NET Core</a></span>
</div>
</div>
</div>
<div class="clearfix"></div>
</footer>
@* Razor section for additional page-specific scripts *@
@RenderSection("scripts", required: false)
</body>
</html>
あなたのプロジェクトを構築し、ライブサイトのウェブサイト上でナビゲーションメニューをテストします。元のレイアウトにはすでにハードコードされた HTML リンクが含まれていたため、ライブサイトでは違いがわかりません。しかし、Xperience 管理インターフェイス(Pages アプリケーション)に別のページを追加したり、ホームと医療センターの項目の順序を変更したりして、メニューの動的機能をテストすることができます。作成した実装では、メニュー項目の変更があった場合、ナビゲーション・メニューに即座に表示されます。
エクスポートされた MEDIO clinic MVC ウェブサイトと MEDIOClinic プロジェクトファイルでパッケージをダウンロードできます。サンプルソリューションとご自身の実装を比較するには、ウェブサイトをサイトアプリケーションの Xperience インストールにインポートするか、Visual Studio で MVC アプリケーションのコードを表示してください。
前のページ: ページコンテンツの表示— 次のページ: Xperience開発の次のステップ
完成したページ: 9/10
原文:https://docs.xperience.io/13tutorial/asp-net-core-development-tutorial/creating-a-navigation-menu