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

添加GiftViewComponent类,继承ViewComponent

using Microsoft.AspNetCore.Mvc;

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

Tips:根据约定,类名结尾必须以 ViewComponent 结尾,继承ViewComponent类,添加Invoke方法

添加Default.cshtml视图文件

在Views文件夹下的Shared文件中添加Components文件夹,在Components文件夹中添加Gift文件夹,在Gift文件夹下添加Default.cshtml视图文件

在Gift.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

12-24 11:44
查看更多