ASP.NET Core使用ViewComponent视图组件

在asp.net mvc中可以轻松使用Html.RenderAction创建局部视图,但在asp.net core中不支持@html.Action()方法,转而使用ViewComponent,本篇博客介绍如何在.net core中使用ViewComponent视图组件

添加GiftViewComponent类,继承ViewComponent类

在InvokeAsync/Invoke方法中定义逻辑,并返回IViewComponentResult。

using Microsoft.AspNetCore.Mvc;

namespace Test.Models
{
    public class GiftViewComponent : ViewComponent
    {
        public IViewComponentResult Invoke()
        {
            return View();
        }
    }
}

Tips:根据约定,类名结尾必须以 ViewComponent 结尾

添加Default.cshtml视图文件

在Views文件夹下的Shared文件中添加Components文件夹,在Components文件夹中添加Gift文件夹,在Gift文件夹下添加Default.cshtml视图文件(必须在此处添加Default.cshtml文件)

视图组件默认名称为Default,可默认命名为Default.cshtml;或可指定视图名称,在调用View方法返回时,将名称一同返回。

在Default.cshtml视图文件中添加局部视图代码

引入视图组件

在需要引入视图组件的地方添加如下代码:

@await Component.InvokeAsync("Gift")

本篇博客只是简单介绍ViewComponent视图组件的使用,ViewComponent的功能十分强大,如有需要可查看官网教程:

https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-2.2#view-components

End!

原文地址:https://www.cnblogs.com/gygg/p/12161681.html