Html.Action(“”,””) ができなくなっている・・ので新しい方法をレビュー。

トップページに9つのCard(Bootstrap)があって、ここにコンテンツをサーバー側で生成させたいです。

これを参照
https://docs.microsoft.com/en-US/aspnet/core/mvc/views/view-components?view=aspnetcore-2.1

View components are similar to partial views, but they’re much more powerful. View components don’t use model binding and only depend on the data provided when calling into it. This article was written using ASP.NET Core MVC, but view components also work with Razor Pages.

A view component:

Renders a chunk rather than a whole response.

Includes the same separation-of-concerns and testability benefits found between a controller and view.

Can have parameters and business logic.

Is typically invoked from a layout page.

 

なるほど。

 

View components are intended anywhere you have reusable rendering logic that’s too complex for a partial view, such as:

  • Dynamic navigation menus
  • Tag cloud (where it queries the database)
  • Login panel
  • Shopping cart
  • Recently published articles
  • Sidebar content on a typical blog
  • A login panel that would be rendered on every page and show either the links to log out or log in, depending on the login state of the user

A view component consists of two parts: the class (typically derived from ViewComponent) and the result it returns (typically a view). Like controllers, a view component can be a POCO, but most developers will want to take advantage of the methods and properties available by deriving from ViewComponent.

 

OK、なるほどII。 ViewComponentっていうクラスがあって、それはViewを戻すと。

 

ViewComponentというクラスはなんぞや。

The view component class

A view component class can be created by any of the following:

  • Deriving from ViewComponent
  • Decorating a class with the [ViewComponent] attribute, or deriving from a class with the [ViewComponent] attribute
  • Creating a class where the name ends with the suffix ViewComponent

Like controllers, view components must be public, non-nested, and non-abstract classes. The view component name is the class name with the “ViewComponent” suffix removed. It can also be explicitly specified using the ViewComponentAttribute.Name property.

A view component class:

  • Fully supports constructor dependency injection
  • Doesn’t take part in the controller lifecycle, which means you can’t use filters in a view component

 

Filtersが使えない?なんのことだろ。 ま、いいや、進もう。

 

このクラスについてるメソッドの説明

 

View component methods

A view component defines its logic in an InvokeAsync method that returns an IViewComponentResult. Parameters come directly from invocation of the view component, not from model binding. A view component never directly handles a request. Typically, a view component initializes a model and passes it to a view by calling the View method. In summary, view component methods:

Define anInvokeAsyncmethod that returns an 

IViewComponentResultTypically initializes a model and passes it to a view by calling the ViewComponent View method

Parameters come from the calling method, not HTTP, there’s no model binding

Are not reachable directly as an HTTP endpoint, they’re invoked from your code (usually in a view). A view component never handles a request

Are overloaded on the signature rather than any details from the current HTTP request

 

ここもちょっとややこしいけど、要するにInvoleAsync メソッドを使ったらViewComponent を返せるってことかな。

 

関係するViewを探す方法はこんならしい。

 

View search path

The runtime searches for the view in the following paths:

  • Views/<controller_name>/Components/<view_component_name>/<view_name>
  • Views/Shared/Components/<view_component_name>/<view_name>

The default view name for a view component is Default, which means your view file will typically be named Default.cshtml. You can specify a different view name when creating the view component result or when calling the View method.

We recommend you name the view file Default.cshtml and use the Views/Shared/Components/<view_component_name>/<view_name> path. The PriorityList view component used in this sample uses Views/Shared/Components/PriorityList/Default.cshtml for the view component view.

 

Viewファイルを置く場所としては、

  • Views/<controller_name>/Components/<view_component_name>/<view_name>
  • Views/Shared/Components/<view_component_name>/<view_name>

この二つがいいのかな。

 

早速クラスを作ってみます

using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace wppTRDCoporateN1.ViewComponents
{
    public class BoxViewComponent : ViewComponent
    {
        public BoxViewComponent()
        {
        }

        public async Task<IViewComponentResult> InvokeAsync(int position)
        {
            // Do something

            string myView = "Default";

            ViewData["Greeting"] = "Hello";

            myView = "_B1";

            return View(myView);
        }
    }
}

View を用意します

<div class="card-body">
 <h5 class="card-title"><i class="far fa-newspaper fa-fw"></i> @ViewData["Greeting"]</h5>
 <hr class="bg-dark-primary" />
 <p class="card-text">
  Description
 </p>
 <p class="text-right">
 <a href="@Url.Action("D", "News", new {@id = ""})" class="btn btn-sm btn-outline-secondary">詳細</a>
 </p>
</div>

ここにいれます

 

呼び元となるIndex.cshtml からは下記のように記載

<!--News 1-->
<div class="col-md-4">
 <div class="card mb-4 box-shadow">
  @await Component.InvokeAsync("Box", new { position=1 })
 </div>
</div>

 

こんな感じにできました。

 

以上

広告

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください