---
title: "ウォークスルー:カスタムロジックでビューコンポーネントを作成する"
slug: "walkthrough--creating-a-view-component-with-custom-logic"
abstract: "カスタムロジックでSitecoreビューコンポーネントを作成する方法。"
---
# ウォークスルー:カスタムロジックでビューコンポーネントを作成する

> !重要以前にアプリを統合していた場合、それは旧版のASP.NETコアレンダリングSDK(バージョン22以前)を使用しています。このSDKは更新を受け取っていないため、[最新のバージョンへのアップグレード](https://doc.sitecore.com/xmc/en/developers/asp-net/latest/asp-net-core-sdk/upgrade-from-v22.html) をお勧めします。

[ビューコンポーネント](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/view-components.html "View components")を使ってコンテンツをレンダリングし、ビューモデルにデータを供給します。ビューコンポーネントは[、部分ビュー](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/partial-views.html "Partial views")や[モデルバウンド](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/model-bound-views.html "Model-bound views")ビューよりも強力なため、C#クラスをサポートし、追加のレンダリングロジックを実装できます。[MicrosoftのASP.NETコアビューコンポーネントに関するドキュメント](https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1)をご覧ください。

従来のビューコンポーネントは [モデルバインディング](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/model-binding.html "Model binding")をサポートしていませんが、[Sitecore ASP.NETレンダリングSDK](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/sitecore-asp-net-rendering-sdk.md "Sitecore ASP.NET Rendering SDK")は[Sitecoreレイアウトサービスの](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/sitecore-layout-service.html "Sitecore Layout Service") 出力にモデルバインディングを提供します。

このウォークスルーでは、ASP.NETコアビューコンポーネントを使ってSitecoreコンテンツをレンダリングしつつ、カスタムロジックを追加・呼び出してビューモデルにデータを追加する方法を実演します。

> !注このドキュメントは [、Getting Startedテンプレートを使用している](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/walkthrough--using-the-getting-started-template.html "Walkthrough: Using the Getting Started template") か、Content ManagementとContent DeliveryインスタンスのPlatformプロジェクト、RenderingHostプロジェクトを含む動作するSitecoreソリューションを持っていることを前提としています。
> 
> [Getting Startedテンプレートのアイテムやプロジェクトの公開、実行、テスト](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/publish,-run,-and-test-the-getting-started-template-projects.html "Publish, run, and test the Getting Started template projects")方法をご覧ください。

このウォークスルーでは、以下の方法を説明します:

-   「My Service」テンプレートを作成します。
-   MyService JSONレンダリングを作成します。
-   MyService JSONレンダリング用のメインプレースホルダーを設定してください。
-   MyProjectのサイトを公開してください。
-   MyServiceのJSONレンダリングをMyProject/ホームページに追加してください。
-   IFakeServiceサービスインターフェースを作成します。
-   FakeServiceサービスクラスを作成します。
-   FakeServiceサービスをスタートアップクラスに登録してください。
-   MyServiceModelモデルを作成します。
-   MyServiceViewComponentのビューコンポーネントクラスを作成します。
-   MyService/Default Razorビューを作成してください。
-   StartupクラスにMyServiceViewComponentのビューコンポーネントを登録します。
-   MyServiceのデータソースにコンテンツを追加してください。

## マイサービステンプレートを作成する

My Serviceテンプレートは、MyServiceデータソースのヘッダーテキストフィールドのセットを定義しています。

My Serviceテンプレートを作成するには:

1.  コンテンツエディターで/sitecore/Templates/Project/MyProjectフォルダを右クリックし、「新しい**テンプレート**を**挿入**」をクリックします。
2.  名前 **を選択する** ダイアログの **Name** 欄で *My Service* を入力し、「 **Next**」をクリックします。
3.  **ロケーション**ダイアログで、選択したパスでテンプレートが作成されているか確認し、「**次へ**」をクリックして**閉じ**ます。コンテンツエディターは自動的にMy Serviceテンプレートを開きます。
4.  My Serviceテンプレートの**ビルダー**タブで、My Service Template Fieldsと2つのフィールドを作成します。
    -   DateHeader (一行文)
    -   ValueHeader (一行文)
5.  My Serviceテンプレートを保存してください。

## MyService JSONレンダリングを作成してください

MyService JSONレンダリングは、My Serviceテンプレートに基づく任意のデータソースの内容をレンダリングできます。

MyService JSONレンダリングを作成するには:

1.  コンテンツエディターで /sitecore/Layout/Renderings/Project/MyProject フォルダを右クリックし、「 **挿入**、 **Jsonレンダリング**」をクリックします。
2.  **メッセージ**ダイアログで*MyService*を入力し、**OK**をクリックします。コンテンツエディターが自動的にMyService JSONレンダリングを開きます。
3.  MyService JSONレンダリングの**コンテンツタブの****エディターオプション**セクションで、以下のフィールドを設定してください:
    -   **Datasource Location**フィールドで./を入力してください。
    -   **Datasource Template** フィールドで **Insert link** をクリックし、**Insert Item** ダイアログで/templates/Project/MyProject/My Service を選択して **Insert** をクリックします。
4.  MyService JSONレンダリングを保存してください。

## MyService JSONレンダリングのメインプレースホルダーを設定してください

Mainプレースホルダーは、設定したレンダリングのみを受け付けます。

MyService JSONレンダリングのMainプレースホルダーを設定するには:

1.  コンテンツエディターで /sitecore/Layout/Placeholder Settings/Project/MyProject/Main プレースホルダーアイテムに移動します。
2.  プレイスホルダー Main 、 **コンテンツ** タブの「 **データ** 」セクションの **「許可されたコントロール** 」フィールドで **「編集**」をクリックします。
3.  「**アイテム選択**」ダイアログの**エディタータブの****「すべて**」ペインで、「Layout/Renderings/Project/MyProject/MyService」をクリックし、青い矢印![blue-arrow.png](https://doc.sitecore.com/api/markdown-image/xp/ja/developers/hd/19/sitecore-headless-development/images/blue-arrow.png)をクリックして、MyService JSONレンダリングを**選択ペ**インにコピーします。そして**「OK」**をクリックします。
4.  Mainのプレースホルダーを保存してください。

## MyProjectのサイトを公開する

**MyProject**のサイトを公開するには:

1.  コンテンツエディターで sitecore/Content/MyProject/Homeへ行ってください。
2.  「 **公開** 」タブで「 **公開サイト**」をクリックします。
3.  「 **Publish Site** 」ダイアログで「 **再公開** 」チェックボックスを選択し、「 **OK」**をクリックします。

## MyServiceのJSONレンダリングをMyProject/ホームページに追加してください

MyService JSONレンダリングをMyProject/HomeページのMainプレースホルダーに追加し、MyServiceデータソースを作成してからページを公開し、レンダリングホストログで出力を見る必要があります。

MyService JSONレンダリングをMyProject/Homeページに追加するには:

1.  エクスペリエンスエディターでMyProject/Homeページに移動します。
    
2.  **ホーム**タブで**「コンポーネント**」をクリックし、「**ここに追加**」ハンドラーのいずれかをクリックして、Mainプレースホルダーにレンダリングを追加できます。
    
3.  「 **レンダリングを選択する** 」ダイアログで「 **My Service** 」をクリックして **選択**します。
    
4.  **「関連コンテンツ選択**」ダイアログの「**Create New Content**」タブの**Name**欄で「*MyServiceデータソース*」を入力し、「**OK」**をクリックします。
    
    > !注Startupクラスに登録するまでUnknown component 'MyService'メッセージがMyServiceViewComponent。
    
5.  MyProject/Homeページを保存してください。
    
6.  **ホーム**タブで**「公開**」をクリックします。
    
7.  「 **アイテム公開** 」ダイアログで「 **スマートパブリッシュ** 」および **「関連アイテム公開** 」のチェックボックスを選択し、「 **公開**」をクリックします。
    
8.  レンダリングホストにアクセスして、MyService JSONレンダリングプリントがUnknown Component 'MyService'か確認してください。
    
9.  レンダリングホストログで、SitecoreレイアウトサービスのレスポンスでMyServiceデータソースIDと空欄ヘッダーテキストを含むMyServiceコンポーネントを確認してください。
    
    {
     "uid": "efe02844-bd57-4d31-be93-384440aa8d0c",
     "componentName": "MyService",
     "dataSource": "{79F7E3DF-DD72-4575-AFB7-64E174AC6401}",
     "params": {},
     "fields": {
     "DateHeader": {
     "value": ""
     },
     "ValueHeader": {
     "value": ""
     }
     }
    }
    
    [Getting Startedテンプレートのアイテムやプロジェクトの公開、実行、テスト](https://doc.sitecore.com/xp/ja/developers/hd/19/sitecore-headless-development/publish,-run,-and-test-the-getting-started-template-projects.md "Publish, run, and test the Getting Started template projects")方法をご覧ください。
    

## IFakeServiceサービスインターフェースの作成

IFakeServiceサービスインターフェースは、FakeService実装が含めるべき内容を定義します。顧客向けソリューションでは、これを現実世界のビジネスロジックを含むサービスに置き換えます。

FakeServiceインターフェースを作成するには:

1.  管理者権限でVisual Studio、Solution ExplorerでRenderingHostプロジェクトを右クリックし、「 **追加**、**新しいフォルダ**」をクリックします。フォルダ名を*Services*にしてください。
    
2.  RenderingHost/Servicesフォルダを右クリックして「**追加**、**新しいアイテム**」をクリックします。
    
3.  「 **新しいアイテムを追加」** ダイアログで:
    
    -   左側のペインで Installed/Visual C#/ASP.NET Core/Codeをクリックします。
    -   中央のペインで「 **インターフェース**」をクリックします。
    -   ダイアログの一番下、 **名前** 欄で IFakeService.cs を入力して **「追加**」をクリックします。
4.  IFakeService.csファイルでは、内容を以下のコードに置き換えます:
    
    using System;
    using System.Threading.Tasks;
    namespace MyProject.Services
    {
     public interface IFakeService
     {
     DateTime FakeDate { get; }
     Task<int> GetFakeValueAsync();
     }
    }
    
5.  IFakeService.csファイルを保存してください。
    

## FakeServiceサービスクラスを作成する

FakeServiceサービスクラスは、MyServiceデータソースのヘッダーテキストの下に表示されるMyServiceViewComponentクラスの日付と値を提供します。

FakeServiceサービスクラスを作成するには:

1.  Visual Studio、Solution ExplorerでRenderingHost/Servicesフォルダを右クリックし、「 **追加**、**新しいアイテム**」をクリックします。
    
2.  「 **新しいアイテムを追加」** ダイアログで:
    
    -   左側のペインで Installed/Visual C#/ASP.NET Core/Codeをクリックします。
    -   中央のパネルで「 **クラス**」をクリックします。
    -   ダイアログの一番下、 **名前** 欄で FakeService.cs を入力して **「追加**」をクリックします。
3.  FakeService.csファイルでは、内容を以下のコードに置き換えます:
    
    using System;
    using System.Threading.Tasks;
    namespace MyProject.Services
    {
     public class FakeService : IFakeService
     {
     public DateTime FakeDate => DateTime.Now;
     public async Task<int> GetFakeValueAsync()
     {
     return await Task.Run(() => new Random().Next());
     }
     }
    }
    
4.  FakeService.csファイルを保存してください。
    

## FakeServiceサービスをStartupクラスに登録してください

FakeServiceサービスであるため、Startupクラスに登録しなければなりません。

StartupクラスでFakeServiceサービス登録するには:

1.  Visual Studio、Solution Explorer、RenderingHostプロジェクトでStartup.csファイルをダブルクリックしてください。
    
2.  Startup.csファイルにMyProject.Services名前空間を追加します:
    
    using MyProject.Services;
    
3.  StartupクラスのConfigureServices法では、FakeServiceを加えます:
    
    public void ConfigureServices(IServiceCollection services)
    {
     services.AddTransient<IFakeService, FakeService>();
    }
    
4.  Startup.csファイルを保存してください。
    

## MyServiceModelモデルの作成

MyServiceViewComponentビューコンポーネントクラスは、MyServiceデータソースのヘッダーテキストとMyServiceModelモデルのサービス日および値をFakeServiceフィールドに組み合わせています。

MyServiceModelモデルを作成するには:

1.  Visual Studio、Solution Explorerでは右クリックでRenderingHost/Modelsを右クリックし、「 **追加**、**新しいアイテム**」をクリックします。
    
2.  「 **新しいアイテムを追加」** ダイアログで:
    
    -   左側のペインで Installed/Visual C#/ASP.NET Core/Codeをクリックします。
    -   中央のパネルで「 **クラス**」をクリックします。
    -   ダイアログの一番下、 **名前** 欄で MyServiceModel.cs を入力して **「追加**」をクリックします。
3.  MyServiceModel.csファイルでは、内容を以下のコードに置き換えます:
    
    using System;
    using Sitecore.AspNet.RenderingEngine.Binding.Attributes;
    using Sitecore.LayoutService.Client.Response.Model.Fields;
    namespace MyProject.Models
    {
     public class MyServiceModel
     {
     public TextField DateHeader { get; set; }
     public TextField ValueHeader { get; set; }
     public DateTime ServiceDate { get; set; }
     public int ServiceValue { get; set; }
     SitecoreContextProperty
     public bool IsEditing { get; set; }
     }
    }
    
    DateHeaderプロパティとValueHeaderプロパティはIFieldから継承し、自動的にSitecore Layout Serviceの応答にバインドされます。このようにしてMyServiceデータソースのヘッダーテキストが入力されます。
    
    ServiceDateおよびServiceValueプロパティはFakeServiceのMyServiceViewComponentクラスによって填入されます。
    
    IsEditingプロパティはSitecoreContextProperty属性とSitecoreContextに束縛されます。
    
4.  MyServiceModel.csファイルを保存してください。
    

## MyServiceViewComponentビューコンポーネントクラスを作成します

MyService JSONレンダリング、FakeServiceサービス、MyServiceModelモデルを作成したら、このウォークスルーの中心となるMyServiceViewComponentクラスを作成できます。

MyServiceViewComponentクラスでは、FakeServiceサービスの内容がMyService/Defaultビューに表示されるためにMyServiceModelモデルのコンテンツに追加されます。ここで任意のカスタムロジックを追加または呼び出すことができます。

MyServiceViewComponentクラスを作成するには:

1.  Visual Studio、Solution ExplorerでRenderingHostプロジェクトを右クリックし、「 **追加**、**新しいフォルダ**」をクリックします。フォルダ名を*ViewComponents*にします。
    
2.  RenderingHost/ViewComponentsフォルダを右クリックして「**追加**、**新しいアイテム**」をクリックします。
    
3.  「 **新しいアイテムを追加」** ダイアログで:
    
    -   左側のペインで Installed/Visual C#/ASP.NET Core/Codeをクリックします。
    -   中央のパネルで「 **クラス**」をクリックします。
    -   ダイアログの一番下、 **名前** 欄で *MyServiceViewComponent.cs* を入力して「 **追加**」をクリックします。
4.  MyServiceViewComponent.csファイルでは、内容を以下のコードに置き換えます:
    
    using System;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using MyProject.Models;
    using MyProject.Services;
    using Sitecore.AspNet.RenderingEngine.Binding;
    namespace MyProject.ViewComponents
    {
     public class MyServiceViewComponent : ViewComponent
     {
     private readonly IViewModelBinder modelBinder;
     private readonly IFakeService fakeService;
    
     // Use the view component support for dependency injection to inject
     // FakeService and the
     // Sitecore.AspNet.RenderingEngine.Binding.IViewModelBinder service.
     public MyServiceViewComponent(IViewModelBinder modelBinder, IFakeService fakeService)
     {
     this.modelBinder = modelBinder;
     this.fakeService = fakeService;
     }
    
     public async Task<IViewComponentResult> InvokeAsync()
     {
     // Bind MyServiceModel to the Sitecore Layout Service response
     // when the view component is invoked.
     var model = await modelBinder.Bind<MyServiceModel>(this.ViewContext);
    
     if (model.IsEditing)
     {
     // Set mock values to be displayed in edit mode only.
     // This avoids invoking FakeService in the Experience Editor and
     // can be very helpful for content authors, especially if
     // FakeService requires authentication or the user values are
     // not available in edit mode.
     model.ServiceDate = DateTime.MinValue;
     model.ServiceValue = 42;
     }
     else
     {
     // Invoke FakeService to populate the date and value of the model.
     var serviceResult = await fakeService.GetFakeValueAsync();
     model.ServiceDate = fakeService.FakeDate;
     model.ServiceValue = serviceResult;
     }
    
     // Return the model to the Default.cshtml Razor view.
     return View(model);
     }
     }
    }
    
5.  MyServiceViewComponent.csファイルを保存してください。
    

## MyService/Default Razorビューを作成する

MyService/Default RazorビューはMyServiceModelモデルにバインドし、ページ上にコンテンツを提示します。

MyService/Defaultビューを作成するには:

1.  Visual Studio、Solution ExplorerでRenderingHost/Views/Shared/Componentsフォルダを右クリックし、「 **追加**、**新しいフォルダ**」をクリックします。フォルダ名を*MyService*にします。
    
    > !注MyServiceフォルダ名はMyServiceViewComponentクラス名と一致しなければなりませんが、接尾辞はViewComponentなしでなければなりません。これがVisual StudioがViews/Shared/Components/MyService/DefaultビューをViewComponents/MyServiceViewComponentクラスに接続する方法です。
    
2.  RenderingHost/Views/Shared/Components/MyServiceフォルダを右クリックして「**追加**、**新しいアイテム**」をクリックします。
    
3.  「 **新しいアイテムを追加」** ダイアログで:
    
    -   左側のペインで Installed/Visual C#/ASP.NET Core/Webをクリックします。
    -   中央のペインで「 **Razor View - Empty**」をクリックします。
    -   ダイアログの一番下、 **名前** 欄で Default.cshtml を入力して **「追加**」をクリックします。
4.  Default.cshtmlファイルでは、内容を以下のコードに置き換えます:
    
    @model MyProject.Models.MyServiceModel
    <h2 asp-for="DateHeader"></h2>
    @Model.ServiceDate.ToString("R")
    <h2 asp-for="ValueHeader"></h2>
    @Model.ServiceValue
    
5.  Default.cshtmlファイルを保存してください。
    

## StartupクラスにMyServiceViewComponentのビューコンポーネントを登録してください

ウェブページでMyServiceViewComponentビューコンポーネントを使用するには、Startupクラスに登録する必要があります。

StartupクラスにMyServiceViewComponentビューコンポーネントを登録するには:

1.  Visual Studio、Solution Explorer、RenderingHostプロジェクトでStartup.csファイルをダブルクリックしてください。
    
2.  Startup.csファイル、Startupクラス、ConfigureServicesメソッド、AddSitecoreRenderingEngineサービス登録で、MyServiceビューコンポーネントオプションを追加してください:
    
    services.AddSitecoreRenderingEngine(options =>
    {
     options
     .AddModelBoundView<ContentBlockModel>("ContentBlock")
     .AddViewComponent("MyService")
     .AddDefaultPartialView("\_ComponentNotFound");
    })
    
    > !注AddViewComponentパラメータはMyServiceViewComponent名と一致しなければなりませんが、接尾辞ViewComponentは使わなければなりません。
    
3.  Startup.csファイルを保存してください。
    

エクスペリエンスエディターやレンダリングホストのMyProject/Homeページを開くと、MyServiceViewComponentビューコンポーネントの出力を確認できます。エラーがないかレンダリングホストログを確認することをお勧めします。

![Illustration showing the Experience Editor with the MyServiceViewComponent view component.](https://doc.sitecore.com/api/markdown-image/xp/ja/developers/hd/19/sitecore-headless-development/images/exp-edit-view-comp-no-headers.png)

![Illustration showing the rendering host with the MyServiceViewComponent view component.](https://doc.sitecore.com/api/markdown-image/xp/ja/developers/hd/19/sitecore-headless-development/images/rend-host-view-comp-no-headers.png)

左のスクリーンショットは、MyServiceViewComponentビューコンポーネントを持つエクスペリエンスエディターを示しています。 No text in fieldヘッダーは、MyServiceデータソースのヘッダーテキストプロパティがまだ入力されていないことを示しています。日付と数字42 、FakeServiceサービスが編集モードでモック値を表示していることを示しています。

右のスクリーンショットは、MyServiceViewComponentビューコンポーネントを持つレンダリングホストを示しています。空のMyServiceデータソースヘッダーのテキストプロパティは表示されず、日付と乱数はFakeServiceサービスがライブモードでライブ値を表示していることを示しています。

## MyServiceデータソースへのコンテンツ追加

レンダリングホストページでヘッダーテキストを取得するには、エクスペリエンスエディターを使ってMyServiceデータソースにコンテンツを追加します。

MyServiceデータソースへのコンテンツ追加:

1.  エクスペリエンスエディターでMyProject/Homeページに移動します。
    
2.  MyServiceデータソースに自分のヘッダーテキスト値を挿入するには、No text in fieldをクリックしてください。
    
3.  MyProject/Homeページを保存してください。
    
4.  **ホーム**タブで**「公開**」をクリックします。
    
5.  「 **アイテム公開** 」ダイアログで「 **スマートパブリッシュ** 」および **「関連アイテム公開** 」のチェックボックスを選択し、「 **公開**」をクリックします。
    
6.  レンダリングホストにアクセスして、ヘッダーテキスト値でMyServiceViewComponentビューコンポーネントが見えるか確認してください。
    
    ![Illustration showing the rendering host page with the MyServiceViewComponent view component and header texts.](https://doc.sitecore.com/api/markdown-image/xp/ja/developers/hd/19/sitecore-headless-development/images/rend-host-view-comp-with-headers.png)
    

> !ヒントプロジェクト内のREADMEファイルと解決策を確認し、追加情報を確認してください。